V. Déhaye V. Déhaye - 1 year ago 66
MySQL Question

Rails association triggers SQL where clause with 'model'.'model_id' instead of 'model'.'id'

In my Card model, I have the following associations :

has_many :sub_cards, ->(obj) { where('parent_card_id = ?', obj.id) },
inverse_of: :parent_card, :class_name => 'Card'
belongs_to :parent_card, class_name: 'Card', optional: true

Whenever I try to use them, for example in the console typing
, I get the following error :

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column
'cards.card_id' in 'where clause': SELECT
= 237 AND (parent_card_id = 237)

In fact, the SQL request has
'cards'.'card_id' = something
, whereas it should be
'cards'.'id' = something
if I refer to my other working associations.
The problem is I can't find where this syntax comes from.

Has somebody ever experienced this issue ?

Thank you in advance for your help.

Answer Source

You can specify which is the foreign_key of the relation by passing the argument like :foreign_key => "some_attribute_id". This can helps. Good luck!


Don't know it this works for you, but I would write that kinda like this:

has_many :sub_cards, :class_name => 'Card', foreign_key: "parent_card_id"
belongs_to :parent_card, class_name: 'Card', foreign_key: "parent_card_id", optional: true

Think you could give a try on something near that. Good luck again!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download