簡體   English   中英

如何在Ruby on Rails中為相關對象創建刪除鏈接?

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

所以我要說我有帖子和評論,節目的網址是/posts/1/comments/1 我想在comments controller destroy方法中創建一個刪除該注釋的鏈接。 我怎么做?

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

在評論控制器中:

  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

從一段時間以前, confirm選項必須包含在data哈希中,否則將被忽略:

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

有時當你在<a>標簽中有<span><i>或嵌套元素時,這種方式使用link_to很困難。 你可以插入使用易於處理的原始HTML,如下所示:

<a class="btn btn-sm" href="/blogs/<%=@blog.id%>" data-method="delete">             
  <i class="pg-trash"></i><span class="bold">Delete</span>
</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM