【发布时间】:2018-12-16 23:11:43
【问题描述】:
假设我有以下模型:
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 结束链接,所以上面的重新加载解决方案并不令人满意。将 includes 替换为 joins 可以解决此问题,但不会急切加载关联:
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,但对于本问题而言,它不会改变任何东西。
标签: ruby-on-rails-3 activerecord associations arel active-relation