简体   繁体   中英

How to clear database columns in Rails

I have a Cart that

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 . 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.

You can clear the items by simply clearing the items association:

@cart.items.clear

as described in 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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