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

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

    You should try this.

    class Thing  :create
    
      def thing_count
          user = User.find(id)
          errors.add(:base, "Exceeded thing limit") if user.things.count >= 5
      end
    end
    

提交回复
热议问题