我有一个Cart
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 :(得分:3)
您只需清除items
关联:
@cart.items.clear
如http://guides.rubyonrails.org/association_basics.html#has-many-association-reference
中所述答案 1 :(得分: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