Rails 3 ActiveRecord 查询,返回模型的所有记录并在单个查询中包含关联记录的计数

发布于 2024-09-30 02:56:22 字数 597 浏览 2 评论 0原文

我有以下模型:

class Keyword < ActiveRecord::Base
  has_many :tags
  has_many :studies, :through => :tags
end

class Tag < ActiveRecord::Base
  belongs_to :keyword
  belongs_to :study
end

class Study < ActiveRecord::Base
  has_many :tags
  has_many :keywords, :through => :tags
end

我想要一个包含所有关键字的数组,对于每个关键字,以及用该关键字标记的研究的计数,这样我就可以说:

<ul>
<% @keywords.each do |keyword| %>
  <li><%= "(#{keyword.number_of_studies}) #{keyword.title}") %></li>
<% end %>
</ul>

我确信这是可能的,问题是:如何?

I have the following models:

class Keyword < ActiveRecord::Base
  has_many :tags
  has_many :studies, :through => :tags
end

class Tag < ActiveRecord::Base
  belongs_to :keyword
  belongs_to :study
end

class Study < ActiveRecord::Base
  has_many :tags
  has_many :keywords, :through => :tags
end

I want an array containing all of the keywords, and for each keyword, and count of the studies tagged with that keyword, so that I can say:

<ul>
<% @keywords.each do |keyword| %>
  <li><%= "(#{keyword.number_of_studies}) #{keyword.title}") %></li>
<% end %>
</ul>

I'm sure this is possible, the question is: how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

做个少女永远怀春 2024-10-07 02:56:22

您可以使用计数器缓存。这会在父对象上保留一个整数值以及子对象的数量。 ActiveRecord 会进行跟踪。

class Post < AR::Base
  has_many :comments
end

class Comment < AR::Base
  belongs_to :post, :counter_cache => true
end

@post.comments_count

如果您确实必须使用一个没有计数器缓存的查询:

@post = Post.find(first, :select => 'posts.*, count(comments.id) as comments_count',:joins => 'left outer join comments on comments.post_id = posts.id', :group => 'posts.id')
@post.comments_count #=> From join query.

如您所见,这很快就会变得丑陋。最好坚持使用计数器缓存,或者执行两个单独的查询。

@post = Post.find(:first) # SELECT FROM posts
@post.comments.count      # SELECT COUNT(1) FROM comments WHERE post_id = ?

You could use the counter cache. This keeps an integer value on the parent object with the number of children. ActiveRecord keeps track.

class Post < AR::Base
  has_many :comments
end

class Comment < AR::Base
  belongs_to :post, :counter_cache => true
end

@post.comments_count

If you really must use one query without the counter cache:

@post = Post.find(first, :select => 'posts.*, count(comments.id) as comments_count',:joins => 'left outer join comments on comments.post_id = posts.id', :group => 'posts.id')
@post.comments_count #=> From join query.

As you can see, this gets ugly fast. It's better to stick with the counter cache, or do two separate queries.

@post = Post.find(:first) # SELECT FROM posts
@post.comments.count      # SELECT COUNT(1) FROM comments WHERE post_id = ?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文