Validate number of nested attributes

前端 未结 3 1981
傲寒
傲寒 2021-01-19 14:50

I have a model with nested attributes :

class Foo < ActiveRecord::Base
    has_many :bar
    accepts_nested_attributes_for  :bar
end

It

3条回答
  •  难免孤独
    2021-01-19 15:20

    Just in case anyone seeing this needs it to work for Rails 3. I think the add_to_base (that Tony and Jeremy use) has been removed so it needs to be like so:

    class Foo < ActiveRecord::Base
      has_many :bars
      accepts_nested_attributes_for  :bar
    
      def validate
        if self.bars.reject(&:marked_for_destruction?).length < 2
          self.errors.add(:base, "Must have at least 2 bars")
        end
      end
    end
    

提交回复
热议问题