Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate number of nested attributes

I have a model with nested attributes :

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

It works fine. However I'd want to be sure that for every Foo, I have at least two Bar. I can't access the bar_attributes in my validations so it seems I can't validate it.

Is there any clean way to do so ?

like image 324
Damien MATHIEU Avatar asked Dec 28 '22 21:12

Damien MATHIEU


1 Answers

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_to_base("Must have at least 2 bars")
    end
  end
end

The controller will take care of building/updating the bars so you just need to see if you have enough.

like image 188
Tony Fontenot Avatar answered Dec 31 '22 11:12

Tony Fontenot