rails has_many minimum collection size update validation

后端 未结 3 1961
闹比i
闹比i 2020-12-25 11:20

I have a has_many association that accepts nested attributes. I need for there to be a minimum of 1 associated object in the collection, so I wrote a custom va

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 12:06

    SooDesuNe

    Yes, validates :foos, :length => {:minimum => 1, :message=>"At least one foo" } is better than the original one, but the same issue still happens.

    To fix it, we could use validate method:

    validate :validate_foos
    
    private
    def validate_foos
      remaining_foos = foos.reject(&:marked_for_destruction?)
      errors.add :foos, "At least one foo" if remaining_foos.empty?
    

    Hope it helps to who encountered the same problem.

提交回复
热议问题