Reputation: 343
I'm trying to validate the dates in my Rails app. I'm using jQuery Datepicker to choose starting and ending date for booking in a library. I want to check before creating new reservation, that there isn't any other reservation in the db, which would be in conflict with one being created. It seems that no matter what dates I'm picking it always throws error "Not available". Is this because I'm using Datepicker, not a standard date_field in Rails?
if Booking.where {
(book_id == self.book_id) &
(((from <= self.from) & (to >= self.from)) |
((from >= self.from) & (to <= self.to)) |
((from >= self.from) & (from < self.to) & (to >= self.to)))
}.any?
errors.add(:from, "Not available")
end
I also tried:
def uniqueness_of_date_range
errors.add(:from, "is not available") unless Booking.where { (from >= self.from) & (from <= self.to) }.count == 0
errors.add(:to, "is not available") unless Booking.where { (to >= self.from) & (to <= self.to) }.count == 0
end
I'm using the squeel gem. I also experimented with SQL, both array and hash syntax, but it gives me errors about syntax (even if it's double-checked, 100% correct).
Booking.where { (from >= self.from) & (from <= self.to) }
and all other trials gives me back even record which shouldn't be returned.
When I use
Booking.where { (from >= self.from) & (from <= self.to) }.pluck(:from).first
and compare it with my self.from, it shows correct answers.
Upvotes: 0
Views: 47
Reputation: 843
My guess is that your date constraint is not working as you intended.
See if this works:
Booking.where {
(existing_booking.book_id == new_booking.book_id) &
(((existing_booking.to >= new_booking.from) & (existing_booking.to <= new_booking.to)) |
((existing_booking.from <= new_booking.to) & (existing_booking.from >= new_booking.from)))
}
Basically it's checking
book_id
to
is between new booking's from
and to
from
is between new booking's from
and to
Honestly, even if this works, I think this creates a terrible SQL query... I hope some others could add some suggestions.
Upvotes: 0