2015-02-06 79 views
1

我是初學者的鐵軌。使用軌道中的複選框刪除多個記錄

我不知道如何刪除使用Rails中的複選框的多條記錄,如果line_item屬於購物車,則使用 。

cart.rb

class Cart < ActiveRecord::Base 
    has_many :line_items, dependent: :destroy 

line_item.rb

class LineItem < ActiveRecord::Base 
    belongs_to :cart 

視圖/推車/ show.html.erb

<%= @cart.line_items.each do |item| %> 
    <td><%= check_box_tag "item_ids[]", item.id %></td> 
<% end %> 

<%= button_to "Delete selected", {action: "destroy_multiple", id: @cart}, method: :delete%> 

carts_controller.rb

def destroy_multiple 
    @cart.destroy_line_item(params[:item_ids]) 
    respond_to do |format| 

     format.html { redirect_to cart_url } 
     format.json { head :no_content } 
    end 
    end 

cart.rb

def destroy_line_item(items) 
    items.errors.empty? 
    ids = items.split(",") 
    ids.each do |id| 
     line_items.destroy(LineItem.find(id)) 
    end 
end 

回答

0

你可以簡單地嘗試

def destroy_multiple 
    @cart.line_items.where(id: params[:item_ids]).destroy_all 
    respond_to do |format| 
    format.html { redirect_to cart_url } 
    format.json { head :no_content } 
    end 
end 
+0

感謝您發表評論!我編輯它。但錯誤的參數數量(1爲0).... – 2015-02-06 11:39:26

+0

請檢查我的更新信息 – 2015-02-06 17:43:58