How to implement a Counter Cache in Rails?

我们两清 提交于 2019-12-04 10:53:48

I ran through a sample rails app with your code and it all worked fine for me.

I would suggest debugging a little more like hurikhan77 is suggesting and see if it is just the @posts / @post issue that dain suggested.

Also, try creating a post and a comment in the console with some very simple content to see if it is working.

$ ruby script/console

# add whatever fields are necessary to create     
> @p = Post.create(:title => "TestPost1")
  # => #<Post id: 3, ...

# again, add whatever is necessary to create
> @c = @p.comments.create(:comment => "TestComment1")
  # => #<Comment id: 8, ...

> Post.find(:last).comments_count
  # => 1

See what that gets you.

/ JP

This might be completely off the mark, but you use @posts then @post?

ArgumentError in CommentsController#create

wrong number of arguments (2 for 0)

You get this error because @comment is not the object you expect. Try to debug this by inserting:

logger.debug @comment.inspect

You'll see something unexpected and it should raise at least an eyebrow. This should be the clou that you assigned the Post.find(...) to @posts but later tried to work with @post.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!