Search code examples
ruby-on-railsparameterseditdestroy

Passing comments_id to controller in Rails app


I am unable to edit/delete comments in a basic Rails MVC, but the trouble I'm having is that the comments_controller looks for the user_id and not the comments_id, because the user_id is the foreign key. My assumption was that Comment.find(params[:id]) would lead to comments_id, but this is npot the case.

This is the last part of my comments_controller:

    def edit
    @comment = Comment.find(params[:id])
    @user = current_user
end

def update
    @comment = Comment.find(params[:id])
    @user = current_user
    @comment.update(comment_params)
    redirect_to @comment
end

def destroy
    @user = current_user
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to comments_path
end 

private
def comment_params
    params.require(:comment).permit(:user_id, :location, :title, :body)
end

The comments in the views that I'm trying to edit/delete look like this:

     <% @user.comments.each do |w| %>
    <tr>
      <td>Location:<%= w.location %></td>       
      <td>Title:<%= w.title %></td>
      <td>Body:<%= w.body %></td>  
      <td><%= link_to 'Edit', edit_comment_path %></td>
      <td><%= link_to 'Destroy', comment_path,
          method: :delete,
          data: { confirm: 'Are you sure?' } %></td><br>
    </tr>
  <% end %>

Thanks for any advice offered :-)


Solution

  • When you edit/destroy your comment, you need to pass the actual comment in the link_to helper. Something like link_to 'Destroy', w, method: :delete, data: { confirm: 'Are you sure?' } will do.

    Similarly with edit: link_to 'Edit', edit_comment_path(w)