gpt4 book ai didi

ruby-on-rails - 这应该在模型中吗?如果是这样,我应该怎么写这个?

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:07 24 4
gpt4 key购买 nike

假设我正在编写一个将产品添加到购物车的函数。

我有一个 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。

等等

所有这些逻辑应该放在哪里?涉及到许多其他模型,所以我很困惑。

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

什么是rails方式?请澄清。

谢谢!

最佳答案

为了详细说明我上面的评论,下面是您的 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

关于ruby-on-rails - 这应该在模型中吗?如果是这样,我应该怎么写这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com