# Has\_many relationship - specify how quantity (how many)

**URL:** <https://www.ruby-forum.com/t/has-many-relationship-specify-how-quantity-how-many/171572>\
**Category:** Rails\
**Created:** [July 5, 2009, 11:12pm UTC](https://www.ruby-forum.com/t/has-many-relationship-specify-how-quantity-how-many/171572 "2009-07-05T23:12:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![benol](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bb73d2/32.png) [@benol](https://www.ruby-forum.com/u/benol)\
**Post date:** [July 5, 2009, 11:12pm UTC](https://www.ruby-forum.com/t/has-many-relationship-specify-how-quantity-how-many/171572/1 "2009-07-05T23:12:30Z")

</div>

Hi,

Is there any way to specify a a validation rule or something for the  
"has\_many’ relationship so that it would count the related objects?

For e.g. I want my Foo object to have maximum of 5 Bar objects in  
has\_many relationship.

M.

---

<div class="post-metadata">

**Author:** ![benol](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bb73d2/32.png) [@benol](https://www.ruby-forum.com/u/benol)\
**Post date:** [July 6, 2009, 12:55am UTC](https://www.ruby-forum.com/t/has-many-relationship-specify-how-quantity-how-many/171572/2 "2009-07-06T00:55:42Z")

</div>

I suppose you could write a custom validator to ensure that no more than  
5  
child objects exist.

On Sun, Jul 5, 2009 at 5:12 PM, Michal B. \<

---

<div class="post-metadata">

**Author:** ![benol](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/bb73d2/32.png) [@benol](https://www.ruby-forum.com/u/benol)\
**Post date:** [July 6, 2009, 1:05am UTC](https://www.ruby-forum.com/t/has-many-relationship-specify-how-quantity-how-many/171572/3 "2009-07-06T01:05:03Z")

</div>

validates :bar\_limit

def bar\_limit  
…  
end

-eric

On Jul 5, 2:12 pm, Michal B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
