如何在与联接关联的 where 子句中使用命名关联?
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
生成:
"SELECT `owners`.* FROM `owners` INNER JOIN `pets` ON `pets`.`owner_id` = `owners`.`id` WHERE (`dogs`.`name` = 'fido')"
请注意,该WHERE
子句正在查找dogs
表而不是pets
表
以供参考:
http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables