簡體   English   中英

ActiveRecord :: Relation不能在join的where子句中使用命名關聯

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

如何在與聯接關聯的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

看來這是預期的行為-您需要在哈希中指定表名,而不是關聯名。 這有點不幸,因為我認為構造查詢更多地基於它們的模型定義,而不是基於它們前面的模式,這將是有用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM