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

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

    try this, just like string:

    class User < ActiveRecord::Base
      has_many :things, :dependent => :destroy
      validates :things, length: {maximum: 4}
    end
    

提交回复
热议问题