应该在模型中吗?如果是这样,我应该怎么写呢?

问题描述

| 假设我正在编写一个将产品添加到购物车的功能。 我有一个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,我想返回某种错误或状态,指出该产品不属于此商店,因此我无法继续。 如果数量为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
,而您在ѭ5中所做的则应在
cart_controller#create
动作中完成。 为了检查这些值,我认为您应该研究自定义验证器     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...