# Validating against other records for bulk creates/updates?

**URL:** <https://www.ruby-forum.com/t/validating-against-other-records-for-bulk-creates-updates/168202>\
**Category:** Rails\
**Created:** [May 18, 2009, 9:48am UTC](https://www.ruby-forum.com/t/validating-against-other-records-for-bulk-creates-updates/168202 "2009-05-18T09:48:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jacib](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/da6949/32.png) [@jacib](https://www.ruby-forum.com/u/jacib)\
**Post date:** [May 18, 2009, 9:48am UTC](https://www.ruby-forum.com/t/validating-against-other-records-for-bulk-creates-updates/168202/1 "2009-05-18T09:48:29Z")

</div>

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?

protected

```
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  
one.”)  
end  
end

end

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  
request).

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 P.

---

<div class="post-metadata">

**Author:** ![jacib](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/da6949/32.png) [@jacib](https://www.ruby-forum.com/u/jacib)\
**Post date:** [May 18, 2009, 6:18pm UTC](https://www.ruby-forum.com/t/validating-against-other-records-for-bulk-creates-updates/168202/2 "2009-05-18T18:18:01Z")

</div>

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 J.
