简体   繁体   中英

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 :-)

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?' } link_to 'Destroy', w, method: :delete, data: { confirm: 'Are you sure?' } will do.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM