Rails: How to limit number of items in has_many association (from Parent)

后端 未结 8 1240
情深已故
情深已故 2021-01-30 11:45

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

8条回答
  •  渐次进展
    2021-01-30 12:04

    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 }
    

提交回复
热议问题