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

后端 未结 8 1177
情深已故
情深已故 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:13

    So if you want a different limit for each user you can add things_limit:integer into User and do

    class User
      has_many :things
      validates_each :things do |user, attr, value|
       user.errors.add attr, "too much things for user" if user.things.size > user.things_limit
      end
    end
    
    class Thing
      belongs_to :user
      validates_associated :user, :message => "You have already too much things."
    end
    

    with this code you can't update the user.things_limit to a number lower than all the things he already got, and of course it restrict the user to create things by his user.things_limit.

    Application example Rails 4 :

    https://github.com/senayar/user_things_limit

提交回复
热议问题