我有模型order.rb,line_items.rb - 其中line_item属于order。我添加了自定义验证,因此订单应该只有line_items才能使用相同的merchant_id
我的问题是:似乎验证工作正常 - 我可以在违反时收到错误,但“line_item”记录仍可在任何情况下保存。有什么想法吗?
Order.rb
validate_on_update :only_one_merchant
def only_one_merchant
merchants = []
for line_item in self.line_items
merchants << line_item.product.merchant_id
end
merchants = merchants.uniq
errors.add(:line_items, "You could only order from one same merchant at time") if merchants.length > 1
end
Order.rb 添加line_item
current_item = LineItem.new(:quantity => quantity)
current_item.variant = variant
current_item.price = variant.price
self.line_items << current_item
答案 0 :(得分:0)
validate_on_update
仅在更新任何记录时检查验证,以便在任何条件下使用validate
Chnage
validate_on_update :only_one_merchant
到
validate :only_one_merchant
&安培;检查它是否有效
答案 1 :(得分:0)
validate :only_one_merchant
def only_one_merchant
merchants = []
for line_item in self.line_items
merchants << line_item.product.merchant_id
end
merchants = merchants.uniq
errors.add(:line_items, "You could only order from one same merchant at time") if merchants.length > 1
end
它将首先解决您的问题这些函数调用然后更新