如何在Ruby on Rails中为相关对象创建删除链接?

Art*_*iro 51 ruby ruby-on-rails hyperlink

所以,假设我有帖子和评论,而节目的网址是/posts/1/comments/1.我想在comments controller destroy方法中创建一个删除该注释的链接.我怎么做?

Ian*_*hop 107

<%= link_to 'Destroy', post_comment_path(@post, comment),
            data: {:confirm => 'Are you sure?'}, :method => :delete %>
Run Code Online (Sandbox Code Playgroud)

在评论控制器中:

  def destroy
    @post = Post.find(params[:post_id])
    @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to post_comments_path(@post) }
      format.xml  { head :ok }
    end
  end
Run Code Online (Sandbox Code Playgroud)

  • 您还必须确保标头中包含<%= javascript_include_tag:all%>或类似标记.否则链接将在那里,但不会尊重:method =>:delete.只是添加这个评论,因为那刚才让我感到困惑.... (14认同)
  • 快速说明:`javascript_include_tag:all`在Rails> 3.1中被删除,应用程序布局默认为`= javascript_include_tag'应用程序"`这将完成同样的事情 (4认同)

Kos*_*sis 9

从一段时间以前,该confirm选项必须包含在data哈希中,否则将被忽略:

<%= link_to 'Destroy',  post_comment_path(@post, comment),
    data: { confirm: 'Are you sure?' }, method: :delete %>
Run Code Online (Sandbox Code Playgroud)


ins*_*ero 5

@post鉴于您的帖子对象有变量

Rails 7 之前

<%= link_to 'Delete comment', post_comment_path(@post, comment),
  method: :delete, data: {confirm: 'Are you sure?'} %>
Run Code Online (Sandbox Code Playgroud)

Rails 7(带 Turbo,开箱即用)

<%= link_to 'Delete comment', post_comment_path(@post, comment),
  data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
Run Code Online (Sandbox Code Playgroud)