2013-12-16 15 views
0

我有一個Cart在Rails中如何清除數據庫列

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

,並在結賬時,我想從購物車中刪除所有items對於給定的user。我怎樣才能做到這一點?

結帳控制器看起來是這樣的:

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 

注:我不想砸Cart並重新創建它,只是明確從項目。

回答

0

描述,我認爲你的車的模型並不一定需要與數據庫的鏈接,你可以把會議中的一切。

你的模型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 

您的項目:

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 

在你的控制器:

class CartController < ApplicationController 

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


    def empty 
    session[:cart] = nil 
    end 
end