JQuery没有在视图中删除正确的行

时间:2015-09-08 01:17:47

标签: jquery ruby-on-rails

我的观点目前看起来像这样:

Restier

我的控制器看起来像这样:

<li class="list" data-id="<%=list.id%>">
  <div class="view" id="<%=list.id%>">
    <input class="toggle" type="checkbox" checked="">
      <%= button_to "Delete", { action: "destroy", id: list.id }, method: :delete, :class => "destroy", remote: true %>
    <label><%= list.name %></label>
  </div>
  <%= form_for(list, remote: :true) do |f| %>
    <%= f.text_field :name, :class => "edit" %>
  <% end %>  
</li>

我当前的destroy.erb.js文件如下所示:

class ListsController < ApplicationController
  def index
    @lists = List.order("created_at DESC")
    @list = List.new
  end

  def create
    @list = List.new(list_params)
    if @list.save
      if request.xhr?
        @lists = List.all
        # somehow only send back the html for the page update
        render :layout => false
      else
        redirect_to root_path
      end
    else
      @lists = List.all
      render :index
    end
  end

  def update
    @list = List.find(params[:id])
    if @list.update(list_params)
      render
    else
      render 'list/show'
    end
  end

  def destroy
    @list = List.find_by(params[:id])
    @list.destroy

    respond_to do |format|
      format.html { redirect_to lists_path }
      format.js #rails default: go to views/todos/destroy.js.erb
    end
  end

  private
    def list_params
      params.require(:list).permit(:name)
    end
end

它正在使用AJAX,但它总是首先删除底行(而不是id,点击)...我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

也许在你的控制器中尝试这样的事情:

def destroy
  list = List.find_by(params[:id])
  list.destroy
  @list_id = params[:id]

  respond_to do |format|
    format.html { redirect_to lists_path }
    format.js #rails default: go to views/todos/destroy.js.erb
  end
end

然后在js:

var id = "<%= @list_id %>";
console.log(id);
$("#" + id).slideUp();

你正在破坏记录,所以我不是百分百肯定,但我认为你不应该引用被破坏记录的属性。此外,请在执行此操作后检查您的控制台,并确保ID符合您的预期。

答案 1 :(得分:1)

def destroy
  # Its better to have local variable as you are not going to need any
  #   instance variable and minimal @instance variables should be use only if required. They are expensive actually
  list = List.find_by(params[:id])
  list.destroy

  respond_to do |format|
    format.html { redirect_to lists_path }
    format.js #rails default: go to views/todos/destroy.js.erb
  end
end

并在views/todos/destroy.js.erb

    console.log(id);
    // No need to save the id in any instance variable as params is available here as well
    $("#<%= h params[:id] %>").slideUp('slow', function(){
     // Better to delete the record from the DOM
     $(this).remove();
    });
  

注意:您不应该直接在DOM中呈现params,而应该转义字符串。 http://api.rubyonrails.org/classes/ERB/Util.html#method-c-h