限制activerecord验证的范围

时间:2014-12-23 21:22:39

标签: ruby-on-rails validation activerecord

在rails购物车应用程序中,我有购物车型号,产品型号和line_item型号:

class Cart < ActiveRecord::Base
  has_many :line_items
  has_one :order
end   

class LineItem < ActiveRecord::Base
  belongs_to :cart
  belongs_to :product
end

class Product < ActiveRecord::Base
end

现在我正在验证交付日期的唯一性(这是一个看起来像“2015年5月”的字符串列)。因此,2015年5月只能订购一种“foo”产品。

class LineItem < ActiveRecord::Base
  ...
  validates :delivery, uniqueness: {scope: :product, message: 'there is already an order for this kind of outfit scheduled for this date'}
  ...
end

问题是,如果在2015年5月2日有一个废弃的购物车,其中有一个line_item计划用于产品“foo”,则验证会启动并阻止用户下订单。

1)我想减少验证的范围,以便它验证跳过那些相关购物车的“purchase_at”属性设置为nil(意味着没有购买)的line_items。

2)成功结账购物车会很好,同一产品的所有其他line_items将在同一天交付,将被删除。这样,其他人同时尝试,只会看到该项目从购物车中消失。

1 个答案:

答案 0 :(得分:1)

使用if中的unlessvalidates选项,如下所示:

class LineItem < ActiveRecord::Base
  belongs_to :cart

  validates :delivery, 
            uniqueness: {scope: :product, message: 'message'},
            unless: Proc.new{ |line_item| line_item.cart.purchased_at.nil? }
end