ActiveRecord::Relation cannot use named association in where clause of join

孤街浪徒 提交于 2019-12-11 05:46:38

问题


How do I use a named association in the where clause associated with a join?

class Pet < ActiveRecord::Base
    belongs_to :owner
end

class Owner < ActiveRecord::Base
    has_many :dogs, :class_name => 'Pet', :foreign_key =>  :owner_id
end


Owner.joins(:dogs).where(:dogs => {:name => 'fido'}).to_sql

generates:

"SELECT `owners`.* FROM  `owners`  INNER JOIN `pets` ON `pets`.`owner_id` = `owners`.`id` WHERE  (`dogs`.`name` = 'fido')"

Note that the WHERE clause is looking in the dogs table instead of the pets table

For reference:

http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables


回答1:


It appears this is the expected behavior - you need to specify the table name in the hash, not the association name. This is a little unfortunate because I think it'd be useful construct queries based more on their model definition and less on schema they sit in front of.



来源:https://stackoverflow.com/questions/4103677/activerecordrelation-cannot-use-named-association-in-where-clause-of-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!