简体   繁体   English

如何清除Rails中的数据库列

[英]How to clear database columns in Rails

I have a Cart that 我有一个Cart

class Cart < ActiveRecord::Base
  belongs_to :user
  has_many :items, :dependent => :destroy
end

and on checkout, I'd like to remove all items from the cart for the given user . 在结帐时,我想从购物车中删除给定user所有items How can I achieve this? 我该如何实现?

Checkout controller looks like this: 结帐控制器如下所示:

  def create
    @order = Order.new(order_params)
    @order.user_id = session[:user_id]
    @cart = Cart.find(session[:cart])

    respond_to do |format|
      if @order.save
        OrderNotifier.received(@order,@cart).deliver
        format.html { redirect_to :controller => :orders, :action => :index }
        format.json { render action: 'show', status: :created, location: @order }
      else
        format.html { render action: 'new' }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

Note: I do not want to drop the Cart and recreate it, just clear it from items. 注意:我不想放下Cart并重新创建它,只需从项目中清除它即可。

You can clear the items by simply clearing the items association: 您可以通过清除items关联来清除items

@cart.items.clear

as described in http://guides.rubyonrails.org/association_basics.html#has-many-association-reference http://guides.rubyonrails.org/association_basics.html#has-many-association-reference中所述

I think your cart model don't necessarily need a link with your database, you can put everything in session. 我认为您的购物车模型不一定需要与数据库链接,您可以将所有内容都放在会话中。

Your model Cart.rb 您的模型Cart.rb

class Cart
   attr_reader :items # and more attributes if necessary

   include ActiveModel::Validations

   def initialize
       @items = [] # you will store everything in this array
   end

   # methods here like add, remove, etc...
end

Your items: 您的物品:

class CartItem
  attr_reader :product # and attributes like quantity to avoid duplicate item in your cart

  def initialize(product)
    @product = product

  end

  # methods here
end

In your controller: 在您的控制器中:

class CartController < ApplicationController

  def find_or_initialize_cart
    session[:cart] ||= Cart.new
  end


  def empty
    session[:cart] = nil
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM