我有2个型号,cart和line_item:
cart.rb& line_item.rb
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
belongs_to :user
class LineItem < ActiveRecord::Base
belongs_to :cart
belongs_to :user
application_controller.rb
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = current_user.cart.create
session[:cart_id] = cart.id
cart
end
如何向购物车添加验证,以便用户最多只能在购物车中添加5件商品?目前我有这个代码,但它不起作用?
def maximum_items_not_more_than_5
if line_items.count > 5
errors.add(:line_items, "must be less than 5")
end
end
答案 0 :(得分:1)
这是一种方法,我会尝试:
class LineItem < ActiveRecord::Base
belongs_to :cart, validate: true # enables validation
然后在Cart模型中,编写自己的自定义验证,如:
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
validate :maximum_items_not_more_than_5 # using custom validation
private
def maximum_items_not_more_than_5
if line_items.count > 5
errors.add(:base, "must be less than 5")
end
end
答案 1 :(得分:0)
为什么line_item
属于user
?肯定是item
:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :carts
end
#app/models/cart.rb
class Cart < ActiveRecord::Base
belongs_to :user
has_many :line_items, inverse_of: :cart
has_many :items, through: :line_items
validate :max_line_items
private
def max_line_items
errors.add(:tags, "Too many items in your cart!!!!!!") if line_items.size > 5
end
end
#app/models/line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :cart, inverse_of: :line_items
belongs_to :item #-> surely you want to specify which item is in the cart?
end
#app/models/item.rb
class Item < ActiveRecord::Base
has_many :line_items
has_many :carts, through: :line_items
end
<强>验证强>
这肯定属于validation领域,特别是custom method:
#app/models/model.rb
class Model < ActiveRecord::Base
validate :method
private
def method
## has access to all the instance attributes
end
end
我还将inverse_of
放入混音中。
您可以在此处查看其工作原理:https://stackoverflow.com/a/20283759/1143732
具体来说,它允许您从特定模型中调用parent
/ child
个对象,从而允许您调用验证&amp;驻留在这些文件中的方法。
在您的情况下,可能谨慎地向line_item
模型添加验证 - 指定单个数量或其他内容。您可以通过设置正确的cart
inverse_of
模型调用此模型中的验证