[英]Should this be in the model? If so, how should I be writing this?
假设我正在编写一个 function,它将将产品添加到购物车中。
我有一个cart.rb model,方法签名如下:
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。 我想返回某种错误或状态,说该产品不属于这家商店,所以我无法继续。
如果数量为 0,我想告诉用户数量必须 > 0。
等等
所有这些逻辑应该在哪里? 还有很多其他模型,所以我很困惑。
我应该使用投票错误集合吗? 或者传回状态码?
什么是铁轨方式? 请说清楚。
谢谢!
为了详细说明我上面的评论,以下是您的Cart
和CartItem
类的外观/工作方式。
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
我认为这应该称为cart_item.rb
并且您在add_product
中所做的应该在您的cart_controller#create
操作中完成。
为了检查值,我认为您应该查看自定义验证器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.