Maximum for has_many relationship?

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?

On Wed, Oct 14, 2009 at 12:08 AM, David [email protected] 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


class BaseballCard < Activerecord::Base

belongs_to :user, :counter_cache => true


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


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


class AddBaseballCardsCountToUsers < Activerecord::Migration
def self.up
add_column :users, :baseball_cards_count, :integer, :default => 0

def self.down
remove_column :users, :baseball_cards_count

Now, you can access the counter_cache as following to check the card


Finally, I would recommend reading more about the counter_cache in AWDwR

Good luck,


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs