# Maximum for has\_many relationship?

**URL:** <https://www.ruby-forum.com/t/maximum-for-has-many-relationship/177261>\
**Category:** Rails\
**Created:** [October 14, 2009, 9:09am UTC](https://www.ruby-forum.com/t/maximum-for-has-many-relationship/177261 "2009-10-14T09:09:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [October 14, 2009, 9:09am UTC](https://www.ruby-forum.com/t/maximum-for-has-many-relationship/177261/1 "2009-10-14T09:09:36Z")

</div>

Im wondering, is there a way to set a limit/maximum for the number of  
objects saved in a has\_many relationship? For example, I have Users  
that have a has\_many relationship with the model BaseballCards. Is  
there a built-in model function to make it so that a User cannot add  
more than 1000 baseball cards?

If not, what would be the best way to go about setting this  
restriction? It seems one could add a baseball\_card\_total column to  
the users table and keep adjusting this column accordingly or perform  
a search for the total before every save?

---

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [October 14, 2009, 10:28am UTC](https://www.ruby-forum.com/t/maximum-for-has-many-relationship/177261/2 "2009-10-14T10:28:03Z")

</div>

On Wed, Oct 14, 2009 at 12:08 AM, David [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> a search for the total before every save?

Hi, you can create a counter\_cache to the belongs\_to of the BaseballCard  
model. For example,

class User \< Activerecord::Base

has\_may :baseball\_cards

end

class BaseballCard \< Activerecord::Base

belongs\_to :user, :counter\_cache =\> true

end

Next, you’ll need to update the users table to contain the following  
field:

baseball\_cards\_count

Thus, your migration for adding such a field will look something like  
this:

add\_baseball\_cards\_count\_to\_users.rb:

class AddBaseballCardsCountToUsers \< Activerecord::Migration  
def self.up  
add\_column :users, :baseball\_cards\_count, :integer, :default =\> 0  
end

def self.down  
remove\_column :users, :baseball\_cards\_count  
end  
end

Now, you can access the counter\_cache as following to check the card  
total:

.baseball\_cards\_count

Finally, I would recommend reading more about the counter\_cache in AWDwR  
3rd  
Edition.

Good luck,

-Conrad
