假設我有以下型號:匹配嵌套模型關聯屬性包括
class Post < ActiveRecord::Base
has_many :authors
class Author < ActiveRecord::Base
belongs_to :post
而且假設Author
模型有一個屬性,name
。
我想通過作者的名字搜索給定作者「alice」的所有帖子。假設有另一位作者「bob」與alice合寫了一篇文章。
如果我使用includes
和where
搜索的第一個結果:
post = Post.includes(:authors).where("authors.name" => "alice").first
你會看到該職位只有一個作家,現在,即使其實還有更多:
post.authors #=> [#<Author id: 1, name: "alice", ...>]
post.reload
post.authors #=> [#<Author id: 1, name: "alice", ...>, #<Author id: 2, name: "bob", ...>]
問題似乎是includes
和where
的組合,它將範圍正確地限制爲所需的帖子,但同時隱藏除匹配的範圍之外的所有關聯。
我想最終得到鏈接的ActiveRecord::Relation
,所以上面的重載解決方案並不令人滿意。通過joins
更換includes
解決了這個,但不急於負荷的關聯:
Post.joins(:authors).where("authors.name" => "alice").first.authors
#=> [#<Author id: 1, name: "alice", ...>, #<Author id: 2, name: "bob", ...>]
Post.joins(:authors).where("authors.name" => "alice").first.authors.loaded?
#=> false
有什麼建議?在此先感謝,我已經在這個問題上徘徊了一段時間。
注意:我認識到,帖子/作者的關聯應該更實際地成爲HABTM,但它不會爲此目的而改變任何內容。 – 2012-02-09 03:46:53