Reputation: 7493
I have the following model which corresponds to teh following table:
PriceAvailability
ID| PRODUCT_ID| VALID_FROM|VALID_TO|PRICE
Basically the table stores prices of a particular product between a specific range of dates. Like a product may cost 10 dollars between 1st Jan 2012 to 3rd May2012 and 12 DOllars from 3rd of May to end of June etc. Thing is that I need to set up a validator that:
I got the idea of setting up validators and even set up a simple validator for the start date however I'm stuck with implemnting this kind of check. How can I do it?
Upvotes: 0
Views: 210
Reputation: 10630
let me know if this works for you:
validate :ensure_unique_date_ranges
def ensure_unique_date_ranges
date_ranges = (products.price_availabilities - [self]).map{ |pa| (pa.valid_from.to_i..pa.valid_to.to_i) }
self.errors[:base] << 'date range is invalid' if date_ranges.detect{ |dr| (dr.to_a & (valid_from.to_i..valid_to.to_i).to_a).empty? }
end
One thing to watch out for is date.to_i. If ranges are big then performance might go down. Try and see if it's acceptable.
Upvotes: 1