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?
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