我将使用通用博客示例。
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
查询 Post 时,如何访问它的关联(即:comments)?
这应该是世界上最简单的事情,但我还没有找到任何关于它的文档。甚至http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interface和http://m.onkey.org/2010/1/22/active-record-query-interface也无济于事,基本上是说“现在有是像连接和包含这样的方法来做与 SQL 语句相同的事情。” 是的,谢谢。
所以这是我想做的非常简单的事情,它们不起作用,但我想要完成的事情应该很明显:
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)
如果不使用带有 SQL 气味的 ruby 代码(从而违背了 Active Record 的目的),我们如何才能做到这些?谢谢 :)