I would like to limit the number of items in an association. I want to ensure the User doesn\'t have more than X Things. This question was asked before and the solution had th
Validating on the current count causes the count to become greater than the limit once the save has completed. The only way I've found way to prevent the create from occurring is to validate that before the create, the number of things is less than the limit.
This is not to say that it isn't useful having a validation on the count in the User model, but doing so doesn't prevent User.things.create
from being called because the user's count collection is valid until the new Thing object is saved, and then becomes invalid after the save.
class User
has_many :things
end
class Thing
belongs_to :user
validate :on => :create do
if user && user.things.length >= thing_limit
errors.add(:user, :too_many_things)
end
end
end
How you investigated using accepts_nested_attributes_for?
accepts_nested_attributes_for :things, :limit => 5
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
That said, I think accepts_nested_attributes_for seems to only be appropriate for certain types of situations. For example, if you were creating a command line API, I think it's a pretty awful solution. However, if you have a nested form it works well enough (most of the time).