Question

I'm learning rails for a course at university, so excuse my ignorance. We have to make a project where users can attend and comment on events. I'm almost done, but the one thing that I can't seem to get working is editing a comment which of course depends on an event.

Here's what I got so so far: In my CommentsController:

def edit
  @event = Event.find(params[:event_id])
  @comment = @event.comments.find(params[:id])
end

def update
  @event = Event.find(params[:event_id])
  @comment = @event.comments.find(params[:id])

  if @comment.update(params[:comment].permit(:user_id, :message))
    redirect_to @event
  else
    render 'edit'
  end
end

the link to the edit-page in the partial comments/_comment.html.erb, (I use the path which shows up in rake routes)

 <%= link_to 'Edit', edit_event_comment_path(@event, comment) %>

and my comments/_form.html.erb partial, of which the form_for I am pretty sure is the source of my error:

<%= form_for([@event, @event.comments.build]) do |f| %>

... 

<p>
  <%= f.label :commenter %></br>
  <%= collection_select(:comment, :user_id, User.all, :id, :name_with_id, {}) %>
</p>


<p>
  <%= f.label :message  %><br />
  <%= f.text_area :message %> <br />
</p>

<p>
  <%= f.submit %>
</p>

<% end %>

What happens at this point is that the form is rendered when clicking the link, but the form shows up empty and submitting creates a new comment in stead of updating the current one. From reading other SO-questions I'm pretty sure I have to call the form_for differently to fix this, but I've got no idea how. Can anyone help? Thanks!

Was it helpful?

Solution

Replace

<%= form_for([@event, @event.comments.build]) do |f| %>

With

<%= form_for([@event, @comment]) do |f| %>

When you say @event.comments.build, it will create a new instance of comment and upon submitting the form a new comment would be created in database. In order to update an existing comment, in edit action you have set @comment instance variable which is the comment you want to edit. So you will need to specify that one in form_for.

Asker's edit for completeness (see comments): I had a comment-form embedded in the show action of the event and so I also had to initialize a comment with Comment.new in the event's show-action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top