嵌套资源和嵌套属性时的路由

时间:2013-09-16 11:21:44

标签: ruby-on-rails ruby ruby-on-rails-3 routes

我有一个Review模型,它是Publication模型的嵌套资源。评论模型具有accept_nested_attributes_for review_comments。我想知道如何显示删除review_commment的删除路径?

<% @review.review_comments.each do |review_comment| %>
   <%= link_to "delete", ???,  method: :delete %>
<% end %>

review.rb

has_many :review_comments, :dependent => :destroy
accepts_nested_attributes_for :review_comments, :allow_destroy => :true

review_comment.rb

belongs_to :review

publication.rb

has_many :reviews

的routes.rb

resources :publications do
  resources :reviews 
end

resources :review_comments

更新

def create
 @review_comment = ReviewComment.new(params[:review_comment])
  if @review_comment.save
    redirect_to @review_comment, notice: 'Review comment was successfully created.'
   ....
end

def destroy
  @review_comment = ReviewComment.find(params[:id])
  @review_comment.destroy
  redirect_to :back, notice: "Deleted" 
end

更新

 review_comments GET      /review_comments(.:format)                               review_comments#index
                       POST     /review_comments(.:format)                               review_comments#create
    new_review_comment GET      /review_comments/new(.:format)                           review_comments#new
   edit_review_comment GET      /review_comments/:id/edit(.:format)                      review_comments#edit
        review_comment GET      /review_comments/:id(.:format)                           review_comments#show
                       PUT      /review_comments/:id(.:format)                           review_comments#update
                       DELETE   /review_comments/:id(.:format)                           review_comments#destroy

2 个答案:

答案 0 :(得分:0)

对于您的路线:

<%= link_to "delete", review_comment,  method: :delete %>


class ReviewCommentsController < ApplicationController
  def destroy
    @review_comment = ReviewComment.find(params[:id])
    @review_comment.destroy
    redirect_to review_comments_path # Or another path
  end
end

答案 1 :(得分:0)

使用除GET之外的任何方法的link_to实际上是一个坏主意,因为可以在新的选项卡/窗口中右键单击并打开链接,并且因为这只是复制url(而不是方法),它将为非-get links。

此外,链接被网页索引蜘蛛点击,即使有问题的链接可能只对登录用户(因此不是蜘蛛)可用,但它仍然是不好的做法。

最好使用button_to,这会让rails生成一个迷你形式来产生相同的结果。

从实际的角度来看,按钮更好(出于上述原因)但从概念的角度来看它们也更好:一般来说,链接应该“带你到某个地方”,而不是按钮应该&#34;做某事&#34;。保持这两个基本功能是分开的。

像这样,

button_to t('general.delete'), :review_comment_path(review_comment), :method => :delete, :confirm => t('review_comment.confirm_delete'), :title => t('review_comment.delete_question')