我有两个型号
Post
has_many :comments
Comment
belongs_to :post
当我想要显示帖子列表及其评论计数时。我通常会在帖子中添加评论。
Post.find(:all,:include => :comments)
显示一些评论帖子。
post.comments.size
我可以创建一个返回评论计数的has_many关系吗?
has_one :comments_count
我可以像这样包含这种关系吗?
Post.find(:all,:include => :comments_count)
答案 0 :(得分:4)
Rails有一个计数器缓存,它会根据关联项的计数自动更新列值。这将允许您在返回posts对象时包含计数。只需在评论时将其添加到belongs_to。
Comment
belongs_to :post, :counter_cache => true
您需要为计数器的帖子添加一个新的整数列:
class AddCounterCacheToPosts < ActiveRecord::Migration
def self.up
add_column :posts, :comments_count, :integer
end
end
答案 1 :(得分:3)
回答你的问题,是的,你可以;但这不是最有效的方法。通常,您会向名为Post
的{{1}}添加一列,并且每comments_count
次CRUD操作都会更新该列。
添加专栏:
Comment
然后在该迁移中添加以下行:
rails g migration add_comment_count_to_post
然后有两种方法可以从这里处理它。
第一个是add_column :posts, :comments_count, :integer, :default => 0
模型中的自定义before_save
和before_destroy
。
Comment
app/models/comment.rb
第二种方法是使用Rails自定义助手:
class Comment << ActiveRecord::Base
belongs_to :post
before_save :update_comments_count
before_destroy :update_comments_count
def update_comment_count
post.update_attribute(:comment_count, post.comments.count)
end
end
app/models/comment.rb