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

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

    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
    

提交回复
热议问题