简体   繁体   中英

Delete link_to for Comment in Nested Routes on Separate Page

I have a situation in my app in which comments are nested inside the blog like this:

resources :blogs do
   resources :comments
end

I have a list of comments on the users#show page in which the user needs to be able to delete comments. My users_controller is like this:

  def show
    @user = User.find(params[:id])
    @comments = Comment.where(approved: false)
  end

My comments_controller delete method looks like this:

 def destroy
    @blog = Blog.find(params[:blog_id])
    @comment = blog.comments.find(params[:id])
    @comment.destroy
    redirect_to blog_path(@blog), notice: 'Comment has been deleted.'
  end

Finally, here is my delete link on the users#show page:

    <% @comments.each do |comment| %>
      <p><strong><%= comment.body %></strong><br />
      <em><%= comment.user.first_name %> <%= comment.user.last_name %></em></p>
      <%= link_to blog_comment_path(@blog, comment), method: :delete, data: { confirm: 'Are you sure?' } do %>
        <i class="icon ion-trash-a"></i>
      <% end %>
      <%= link_to approve_comment_path(comment), method: :post do %>
        <i class="icon ion-checkmark"></i>
      <% end %>
    <% end %>

I'm getting the following error:

No route matches {:action=>"show", :blog_id=>nil, :controller=>"comments", :id=>"1"} missing required keys: [:blog_id]

Can anyone see where I'm going wrong?

You've not defined @blog yet, so @blog is nil

You can edit that like this

<%= link_to blog_comment_path(comment.blog, comment), method: :delete, .... %>

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