Rails validation -- error is generated , but record is still saved
I have models order.rb , line_items.rb -- where line_item is belongs to order. I've added custom validations, as such an order should only have line_items all with same merchant_id
My question is : it seems the validation is working fine -- i am able to get the error whenever it is violated, but "line_item" records are still saved in any situation. Any idea?
Order.rb
validate_on_update :only_one_merchant
def only_one_merchant
        merchants = []
        for line_item in self.li开发者_开发问答ne_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 adding line_item
  current_item = LineItem.new(:quantity => quantity)
  current_item.variant = variant
  current_item.price   = variant.price
  self.line_items << current_item
validate_on_update will check validation only when you update any record to validate the record in anycondition use validate
Chnage
validate_on_update :only_one_merchant
to
validate :only_one_merchant
& Check if it works or not
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 
It will solve your problem first these function call and then update
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论