2013-04-30 83 views
7

我有多個使用複選框刪除的問題。當我刪除多個記錄時,它獲得了複選框的ID,但它傳遞一個方法名稱作爲參數,並顯示我錯誤。Rails 3通過複選框破壞多條記錄

這裏是我的代碼,

**In my Controller method :** 
    def destroy 
    @ticket = current_user.tickets.find(params[:ticket_ids]) 
    @ticket.destroy 

    respond_to do |format| 
    format.html { redirect_to tickets_url } 
    format.json { head :no_content } 
    end 
    end  


def destroy_multiple 
    Ticket.destroy(params[:tickets]) 

    respond_to do |format| 
    format.html { redirect_to tickets_path } 
    format.json { head :no_content } 
    end 
end 

**In my index.html.erb** 

<%= form_tag destroy_multiple_tickets_path, method: :delete do %> 
. 
. 
<td class="table-icon"> 
    <%= check_box_tag "ticket_ids[]", ticket.id %> 
</td> 
. 
. 
<%= submit_tag "Delete selected" %> 

**In routes.rb** 

resources :tickets do 
    collection do 
    delete 'destroy_multiple' 
    end 
end 

它表明我這個錯誤::::

Couldn't find Ticket with id=destroy_multiple [WHERE "tickets"."user_id" = 1] 

通行證arguement ::::

{"utf8"=>"✓", 
    "_method"=>"delete", 
    "authenticity_token"=>"yHeRR49ApB/xGq1jzMTdzvix/TJt6Ysz88nuBEotHec=", 
    "ticket_ids"=>["11", 
    "12"], 
    "commit"=>"Delete selected", 
    "id"=>"destroy_multiple"} 

回答

3

Ticket.destroy(array_of_ids) 
2

嗨,更新您的控制器代碼同樣..

def destroy_multiple 
@tickets = Ticket.find(params[:ticket_ids]) 
@tickets.each do |ticket| 
ticket.destroy 
end 
end 
+0

其中u使用 「@ticketsts」 這個???這是更正和完善的代碼....「Ticket.destroy(params [:ticket_ids])」 – SSR 2013-06-21 05:58:56

+0

它的錯字,我已經糾正它@SSR – Radhakrishna 2013-09-25 11:03:43

2

嘗試此

Ticket.where(:id => params[:ticket_ids]).destroy_all 
4

步驟:1 在routes.rb中

resources :tickets do 
    collection do 
    delete 'destroy_multiple' 
    end 
end 

步驟:2在_form.html.erb

<%= form_tag destroy_multiple_tickets_path, method: :delete do %> 
    <td class="table-icon"> 
    <%= check_box_tag "ticket_ids[]", ticket.id %> 
    </td> 
    <%= submit_tag "Delete selected" %> 
<%end%> 

STPE:3在控制器

def destroy_multiple 
    Ticket.destroy(params[:tickets]) 
    respond_to do |format| 
     format.html { redirect_to tickets_path } 
     format.json { head :no_content } 
    end 
end