How to implement a Counter Cache in Rails?

Posted by yuval on Stack Overflow See other posts from Stack Overflow or by yuval
Published on 2010-06-02T07:43:59Z Indexed on 2010/06/02 8:03 UTC
Read the original article Hit count: 379

I have a posts controller and a comments controller. Post has many comments, and comments belong to Post. The associate is set up with the counter_cache option turned on as such:

#Inside post.rb
has_many :comments

#Inside comment.rb
belongs_to :post, :counter_cache => true

I have a comments_count column in my posts table that is defaulted to zero, as such:

add_column :posts, :comments_count, :integer, :default => 0

In the create action of my comments controller, I have the following code:

def create
  @posts = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment])
  if @comment.save
    redirect_to root
  else
    render :action => 'new'
  end
end

My problem: when @comment.save is called, I get the following error:

ArgumentError in CommentsController#create

wrong number of arguments (2 for 0)

Removing :counter_cache => true from comment.rb completely solves the problem, so I'm assuming that it is the cause of this vague error. What am I missing here? How can I save my comment and still have rails take care of my counter_cache for my post?

Thanks!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about error