TopperH
TopperH

Reputation: 2223

Restrict the scope of an activerecord validation

In a rails shopping cart app I have a cart model, a product model and a line_item model:

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

Right now I'm validating the uniqueness of the delivery date (that is a string column that looks like "May 2015") against the product. So only one product "foo" can be ordered for May 2015.

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

The problem is that if there is an abandoned cart that has a line_item scheduled for product "foo" on "May 20152 the validation kicks in and prevents the user for making the order.

1) I want to reduce the scope of my validation so that it validates skipping those line_items whose related cart has the "purchased_at" attribute set to nil (meaning that the purchase was not made).

2) It would be nice upon the successful checkout of a cart, that all the other line_items for the same product set for delivery on the same date, would be deleted. This way other people trying to but at the same time, would just see the item disappear from the cart.

Upvotes: 0

Views: 1158

Answers (1)

SHS
SHS

Reputation: 7744

Use the if or unless options in your validates like so:

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

Upvotes: 1

Related Questions