On Wed, Oct 14, 2009 at 12:08 AM, David
<dlynam-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
>
> 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:
<instance-of-user-model>.baseball_cards_count
Finally, I would recommend reading more about the counter_cache in AWDwR
3rd
Edition.
Good luck,
-Conrad
>
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---