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

Bla*_*man 1 ruby ruby-on-rails

假设正在编写一个将产品添加到购物车的功能.

我有一个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
Run Code Online (Sandbox Code Playgroud)

所以我必须传递大约4个其他模型,然后进行一些健全性检查.

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

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

等等

所有这些逻辑应该在哪里?还有很多其他模型,所以我很困惑.

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

什么是铁轨方式?请澄清.

谢谢!

Jor*_*ing 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
Run Code Online (Sandbox Code Playgroud)