I just created new columns in my database for my micropost table and these columns were vote_count comment_count and I want to connect it to the Vote models vote_up count and the Comment models comment count. Since I just added these columns although there were votes and comments, how do I connect these other models to the micropost model to fill in the new columns. Any suggestions are much appreciated!
Micropost Model
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
It looks like what you’re trying to do is use a
counter_cache, which rails supports, but you’ve got the names of the columns wrong.You want to add a
comments_countand avotes_countcolumn to your database instead of the ones that you have.Then you can hook it up to your models as follows:
The votes half of it is a bit more tricky since you’re using some extra code with your
acts_as_votablemodule, but counter caches are the way that you want to go if I understand you correctly.Here is more info on them: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html