Rails计算列匹配ID的行数

时间:2013-01-10 19:35:17

标签: mysql ruby-on-rails ruby count

所以我有一个帖子模型和投票模型,其中投票与post_id的帖子相关联。

帖子模型

class Post < ActiveRecord::Base
  attr_accessible :comment_count, :downvote, :id, :text, :title, :upvote, :url, :user_id, :users_voted_up_by, :users_voted_down_by

  serialize :users_voted_up_by
  serialize :users_voted_down_by

  belongs_to :user

  has_many :votes
end

投票模型

class Vote < ActiveRecord::Base
  attr_accessible :direction, :post_id, :type, :voter_id

  belongs_to :user

  belongs_to :post

  belongs_to :comment
end

我需要在数据库中查询Votes表中我的循环中当前post_id帖子的所有行:

<% @posts.each do |post| %>
    <%= Vote.count(:post_id, params[:post_id]) %>
<% end %>

但这只计算每一行,我可以写什么以便它们相关联?

1 个答案:

答案 0 :(得分:3)

建议的方法是在查询中使用分组:

<% vote_counts = Vote.group(:post_id).
        where(:post_id => @posts.map(&:id)).count %>
<% @posts.each do |post| %>
  <%= post.id %>: <%= vote_counts[post.id] || 0 %>
<% end %>

分组查询的优点是它只能访问数据库一次。如果您因某些不可思议的原因而希望获得每个帖子的单一计数,您可以使用:

<% @posts.each do |post| %>
  <%= post.id: %> <%= post.votes.count %>
<% end %>

不要让第二种方法的简单性欺骗你。它要求麻烦,因为它涉及N + 1模式。