问题
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