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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1317448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:39:41  来源:igfitidea点击:

How to create a delete link for a related object in Ruby on Rails?

ruby-on-railsrubyhyperlink

提问by Artilheiro

So let's say I have Posts and Comments and the url for show is /posts/1/comments/1. I want to create a link to delete that comment in the comments controller destroy method. How do I do that?

所以假设我有帖子和评论,并且显示的 url 是/posts/1/comments/1. 我想创建一个链接以在评论控制器销毁方法中删除该评论。我怎么做?

回答by Ian Bishop

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

in comments controller:

在评论控制器中:

  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

回答by Kostas Rousis

Since some time ago, the confirmoption has to be included in a datahash, otherwise it will be silently ignored:

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

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

回答by aks

Sometimes when you have <span>, <i>or nested elements inside of a <a>tag this way link_to use is difficult. You can inseted use raw HTML which is easy to handle, like so:

有时,当你有<span><i>或内部嵌套元素<a>标签这样的link_to使用是困难的。您可以插入使用易于处理的原始 HTML,如下所示:

<a class="btn btn-sm" href="/blogs/<%[email protected]%>" data-method="delete">             
  <i class="pg-trash"></i><span class="bold">Delete</span>
</a>