2011-06-13 94 views
1

说我正在写一个函数,将产品添加到购物车。这应该在模型中吗?如果是这样,我该如何写这个?

我有一个cart.rb模型和方法签名的样子:

def self.add_product(store, user, product, quantity, ...) 
    # store.id == product.store_id 
    # quantity > 0 ? 
    # product is active? 
    # if product is in cart, update quantity 

end 

所以我必须要通过在各地的其他4种型号,然后到一些理智的检查也。

因此,如果store.id!= product.store_id,我想返回某种错误或状态,说产品不属于这个商店,所以我不能继续。

如果quanitity是0,我想告诉数量必须是用户> 0

这一切的逻辑应该在哪里?还有很多其他的模型,所以我很困惑。

我应该使用投票错误集合吗?或者传回状态代码?

什么是导轨方式?请澄清。

谢谢!

+0

购物车模型是什么样的?对我来说,购物车应该是一个简单的容器/收藏模型,然后有例如存储数量等的CartItem模型和“belongs_to:cart”。那么你的“完整性检查”可能只是对CartItem模型的验证。 – 2011-06-13 15:32:13

回答

5

向上面阐述我的意见,这里是如何你CartCartItem类可能看起来/工作。

class Cart < ActiveRecord::Base 
    has_many :items, :class_name => 'CartItem' 
    belongs_to :user # one user per cart 
    belongs_to :store # and one store per cart 
end 

class CartItem < ActiveRecord::Base 
    belongs_to :cart 
    belongs_to :product 

    validates_presence_of :cart, :product 

    # sanity check on quantity 
    validates_numericality_of :quantity, :greater_than => 0, 
             :only_integer => true 

    # custom validation, defined below 
    validate :product_must_belong_to_store 

    protected 
    def product_must_belong_to_store 
    unless product.store_id == cart.store_id 
     errors.add "Invalid product for this store!" 
    end 
    end 
end 

# Usage: 

# creating a new cart 
cart = Cart.create :store => some_store, :user => some_user 

# adding an item to the cart (since `cart` already knows the store and user 
# we don't have to provide them here) 
cart_item = cart.items.create :product => some_product, :quantity => 10 
0

我认为这应该被称为cart_item.rb并且您在做什么add_product应该在您的cart_controller#create操作中完成。

为了检查值,我觉得你应该考虑自定义validators