简体   繁体   English

Rails关联使用'model'。'model_id'而不是'model'。'id'触发SQL where子句

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

In my Card model, I have the following associations : 在我的Card模型中,我具有以下关联:

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 c.sub_cards , I get the following error : 每当我尝试使用它们时,例如在控制台中键入c.sub_cards ,都会出现以下错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'cards.card_id' in 'where clause': SELECT cards .* FROM cards WHERE cards . ActiveRecord :: StatementInvalid:Mysql2 :: Error:“ where子句”中的未知列“ cards.card_id”:SELECT cards 。* FROM cards WHERE cards card_id = 237 AND (parent_card_id = 237) card_id = 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. 实际上,SQL请求具有'cards'.'card_id' = something ,但是如果我引用其他工作关联,则应为'cards'.'id' = something 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. 预先感谢您的帮助。

You can specify which attribute is the foreign key of the relation by passing :foreign_key => "some_attribute_id" . 您可以通过传递:foreign_key => "some_attribute_id"来指定哪个属性是关系的外键。 Hope this helps. 希望这可以帮助。 Good luck! 祝好运!

EDIT: 编辑:

Don't know if this works for you, but I would write it kinda like this: 不知道这是否适合您,但我会这样写:

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

I think you could give this a try, or something near it. 我认为您可以尝试一下或尝试一下。 Good luck again! 再次祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM