2 "belongs_to :counter_cache => true" updates 1 counter?

I have podcasts with comments. Each comment has a user. When I post a
comment, the podcast’s comments_count increments but the user’s
comments_count does not. I think my issue lies in the way I’m saving
the comment (from within podcast_controller. Don’t currently have a
comment controller), but don’t know how to do it any other way. Both
podcasts & users tables have the comments_count field as
integer/default=0.

comment.rb:
belongs_to :podcast, :counter_cache => true
belongs_to :user, :counter_cache => true

podcast.rb:
has_many :comments

user.rb:
has_many :comments

My form tag is sitting in a view coming off my podcast_controller.rb
file:
<%= form_tag :action => “comment”, :id => @podcast %>

Here is my podcast_controller#comment method:
def comment
@comment =
Podcast.find(params[:id]).comments.create(params[:comment])
@comment.user_id = current_user.id # I have ActsAsAuthenticated
installed
@comment.save
flash[:notice] = “Added your comment.”
redirect_to :action => “show”, :id => params[:id]
end

I get the new comment, I see the flash notice, comments_count increments
in the podcast table, the correct user id is entered into the user_id
field in comments table, but NO increment on the comments_count field in
the users table.

I sense I may need to create a comments controller and put a create
method in there. But how would I call that method from a view off my
podcast_controller ?

I sense I may need to create a comments controller and put a create
method in there. But how would I call that method from a view off my
podcast_controller ?

Or could it be that because I am grabbing the user id from
current_user.id (which gets the id from session[:user] I believe) the
comments model isn’t associated with the correct user and is simply
populating the user_id field blindly? I don’t know what magic happens
with the objects as opposed to providing an id…if there’s any dif at
all?

Here’s the solution! Got it off the rails IRC channel. Love those
guys!

Still in my podcast controller:

def comment
@comment = Podcast.find(params[:id]).comments.create(params[:comment])
@comment.user = current_user #This was the offending line!
@comment.save
flash[:notice] = “Added your comment”
redirect_to :action => “show”, :id => params[:id]
end

I don’t think I can extrapolate how to extend this correctly if I ever
had the need for three belongs_to, but for now, this is perfect.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs