2

我将使用通用博客示例。

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-interfacehttp://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 的目的),我们如何才能做到这些?谢谢 :)

4

2 回答 2

0

如果你在 Post 上为评论设置了counter_cache,你可以直接看到它有多少评论,而无需查询,这使它更容易和更快。

这将解决您提出的第一个和最后一个问题。

然后你可以像这样查询它们,

  Post.where(:comments_count >= 10)
  Post.order(:comments_count)

但是你最好为此设置范围。

我不确定你想对第二个问题做什么,你想显示当前用户评论过的所有帖子吗?

于 2010-10-20T10:26:29.150 回答
-1

Post.where(:comments.count >= 10)

Post.find(:all).select{|p| p.comments.count >= 10)

Post.where(:comments.author_id == current_user.id)

Post.find(:all).select{|p| p.comments.select{|c| c.author_id == current_user.id } }

Post.order(:comments.count)

Yikes, this one beats me.

嘿,我的两篇文章都对 SQL 有点重。我知道人们用

Post.find(:all, :conditions => blah blah blah..

但我不知道该怎么说。对不起。

于 2010-10-20T10:53:55.863 回答