bugfix> ruby-on-rails > 投稿

index.html.erb のコード : remote:true によるajaxの使用

<% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.description %></td>         
      <td><%= link_to 'Destroy', article_path(article),
              method: :delete, remote:true,
              data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>

ArticlesController のコード:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
    DatChat.reset_column_information()
    @dat_chat= DatChat.all    
    #render plain: @dat_chat.inspect
    return [@articles, @dat_chat]
  end
  def show
    @article = Article.find(params[:id])
  end 
  def destroy
    @article = Article.find(params[:id])
    @article.destroy   
    redirect_to articles_path
  end
end

Destroy機能のステータスを取得し、メッセージ削除 OK を表示する方法または Fail

回答 2 件
  •  def destroy
        @article = Article.find(params[:id]) 
         respond_to do |format| 
          if @article.destroy 
            format.js {render locals: {message: "Ok"}}
          else
            format.js {render locals: {message: "Fail"}}
          end
        end
      end
    
    

  • 私の問題は解決しました: html:

    <td><%= link_to 'Destroy', article_path(article),remote: true,
                  method: :delete,remote: true,class: "destroy-product",
                  data: { confirm: 'Are you sure?' } %></td>
    
    

    ArticlesController のコード  :

    >  @article = Article.find(params[:id])        
    >      respond_to do |format| 
    >       if @article.destroy            
    >         format.js { flash.now[:notice] = "OK" }
    >       else 
    >         format.js { flash.now[:notice] = "Fail" }
    >       end 
    >      end
    
    

    destroy.js.erb:

    alert("<%= j flash[:notice] %>");
    $('.destroy-product').bind('ajax:success', function() {
       $(this).closest('tr').fadeOut();
    });
    
    

あなたの答え