Rails 4.2.5 link_to删除方法

时间:2016-02-14 02:12:14

标签: ruby-on-rails destroy

我对link_to帮助程序的嵌套删除方法有疑问。

以下是我的路线:

resources :restaurants, only: [:new, :show, :edit, :index,:create] do
  resources :reservations, only: [:new, :show, :edit, :index, :create]
  resources :reviews
end

以下是我的评论控制器操作:

def destroy
  @review = Review.find(params[:id])
  @review.destroy
end

user#show上的代码:

<div class="panel-body">
<h1> <%= pluralize(@user.reviews.count ,'review') %> from <%=      @user.name %> </h1>
    <% @user.reviews.order(created_at: :desc).each do |review| %>
    <ul>
      <li><em>Review for restaurant: </em><%= review.restaurant.name %></li>
      <em>Review comment: </em> <%= review.comment %></br>
      <%= link_to 'edit comment', edit_restaurant_review_path(review.restaurant_id, review.id) %>
      <%= link_to 'delete comment', restaurant_review_path( @user, review.id ) , method: :delete, data:{confirm:"are you sure you want to delete this review"} %>
    </ul>
    <% end %>
</div>

这是我的路线:

restaurant_reviews GET    /restaurants/:restaurant_id/reviews(.:format)               reviews#index
                        POST   /restaurants/:restaurant_id/reviews(.:format)               reviews#create
  new_restaurant_review GET    /restaurants/:restaurant_id/reviews/new(.:format)           reviews#new
 edit_restaurant_review GET    /restaurants/:restaurant_id/reviews/:id/edit(.:format)      reviews#edit
      restaurant_review GET    /restaurants/:restaurant_id/reviews/:id(.:format)           reviews#show
                        PATCH  /restaurants/:restaurant_id/reviews/:id(.:format)           reviews#update
                        PUT    /restaurants/:restaurant_id/reviews/:id(.:format)           reviews#update
                        DELETE /restaurants/:restaurant_id/reviews/:id(.:format)           reviews#destroy

我似乎无法删除我的评论。我传递了错误的变量吗? 到'restaurant_review_path'?我的路线似乎是正确的。正如我的编辑link_to助手正在工作。

1 个答案:

答案 0 :(得分:2)

restaurant_review_path( @user, review.id )错了。您将@user作为 restaurant 参数传递,这将生成一个ID错误的链接。

您应该给它一个餐馆(或餐馆ID)和评论,而不是用户和评论ID,就像您在上一行使用编辑链接一样。

restaurant_review_path(review.restaurant_id, review.id)