Forum: Ruby on Rails Validating against other records for bulk creates/updates?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
B4a04ecbe2386b483c36695938f1c320?d=identicon&s=25 Jacob Patton (Guest)
on 2009-05-18 09:48
(Received via mailing list)
I've got a OpeningHour model in my application, which keeps tracks of
a store's opening times (like Monday 9am-12pm, and then 1pm-5pm).  I
want to make sure that the opening hours don't overlap, and if I do
something like:

class OpeningHour < ActiveRecord::Base

  validate  :overlapping_openings?


    def overlapping_openings?
      if OpeningHour.count_by_sql(["SELECT COUNT(id) FROM
opening_hours WHERE
        account_id = ? AND day_of_week = ? AND ends >= ? AND begins
<= ?",
        account_id, day_of_week, ends, begins]) > 0
        errors.add_to_base("This opening hour overlaps with another


this will work if I insert the opening hours one at a time.  When I
attempt to create multiple opening hour objects at once, however, I
can see in the logs that all of the database selects (to validate
against overlapping openings) occur at the start of the request, and
then the new opening hours are inserted.  What that means is that if
the user submits new, overlapping opening hours, the validation passes
(incorrectly, since these opening hours overlap with each other, but
they *don't* overlap with any other in the database before the

Can someone recommend how I can make ActiveRecord validate each new
object against the records in the database, even those that are
created during the same request?

Thanks very much,

Jacob Patton
6883e5ef03484d4fcef507d7b4f1d243?d=identicon&s=25 Matt Jones (Guest)
on 2009-05-18 18:18
(Received via mailing list)
I think you'd be better off validating this in the whatever model
account_id links to - then you can check the members of the
association against each other, even if they haven't been saved yet.

--Matt Jones
This topic is locked and can not be replied to.