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

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

    You could try validates_length_of and validates_associated:

    class Client < ActiveRecord::Base
    
      has_many :orders
      validates :orders, :length => { :maximum => 3 }
    
    end
    
    class Order < ActiveRecord::Base
    
      belongs_to :client
      validates_associated :client
    
    end
    

    A quick test shows that the valid? method works as expected, but it does not stop you from adding new objects.

提交回复
热议问题