使用rails中的复选框删除多个记录

时间:2015-02-06 07:29:04

标签: ruby-on-rails ruby-on-rails-4

我是初学者。

我不知道如何使用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

3 个答案:

答案 0 :(得分:0)

使用delete_alldestroy_all

def destroy_multiple
  LineItem.delete_all(:id => params[:item_ids])

答案 1 :(得分: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

答案 2 :(得分:0)

我的博客应用

https://drive.google.com/open?id=1IF3xNRkPLSAHc-cD3I2sH3tYkb9WADeu

第5条-使用复选框删除多条记录

articles / index.html.erb

...
<%= form_tag destroy_selected_path, method: :delete,remote: true do %>
<table>
...
<% @articles.each do |article| %>
<tr>
<td><%= check_box_tag "blog_articles[]", article.id %></td>
<td><%= article.title %></td>
........
</table>
<%= submit_tag 'Delete selected' %>
<% end %>

articles_controller.rb

...
def destroy
if params[:blog_articles]
Article.destroy(params[:blog_articles])
else
@article = Article.find(params[:id])
@article.destroy
end
redirect_to articles_path
end
...

routes.rb

...
resources :articles do
    resources :comments
end
get '/articles/destroy_selected', to: 'articles#destroy_selected', as: 
:destroy_selected
....