我刚刚在我的数据库中为我的微博表创建了新的列,这些列是vote_count comment_count,我想将它们连接到投票模型、vote_up计数和注释模型注释计数。由于我只是添加了这些列,尽管有投票和评论,我如何连接这些其他模型到微博模型,以填写新的列。任何建议都是非常感谢的!
微柱模型
class Micropost < ActiveRecord::Base
attr_accessible :title, :content, :view_count
acts_as_voteable
belongs_to :school
belongs_to :user
has_many :comments
has_many :views
accepts_nested_attributes_for :comments
end发布于 2012-03-03 19:01:24
看起来,您要做的是使用rails支持的counter_cache,但是列的名称是错误的。
您希望向数据库中添加一个comments_count和一个votes_count列,而不是您所拥有的。
然后,您可以将其连接到您的模型,如下所示:
class Micropost< ActiveRecord::Base
attr_accessible :title, :content, :view_count
acts_as_voteable
belongs_to :school
belongs_to :user
has_many :comments, :counter_cache => true
has_many :views
accepts_nested_attributes_for :comments
end由于您在acts_as_votable模块中使用了一些额外的代码,其中一半的选票比较棘手,但是如果我正确理解您的话,计数器缓存是您想要的方式。
下面是关于它们的更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
https://stackoverflow.com/questions/9548857
复制相似问题