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
In Rails 4, perhaps earlier versions you can simply validate on the value of the counter_cache.
class User
has_many :things
validates :things_count, numericality: { less_than: 5 }
end
class Thing
belongs_to :user, counter_cache: true
validates_associated :user
end
note that I've used :less_than because :less_than_or_equal_to would allow the things_count to be 6 since it is validated after the counter cache update.
If you want to set a limit on a per user basis, you can create a things_limit column to dynamically compare with the limit value you've set.
validates :things_count, numericality: { less_than: :things_limit }