Checking the 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 great. However, I would like to be sure that for every Foo I have at least two bars. I cannot access bar_attributes in my checks, so it seems like I cannot check it.

Is there any clean way to do this?

+4
source share
3 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 creating / updating the bars, so you just need to make sure that you have enough.

+7
source

Tony's answer will not actually handle the case when existing Foo lines are deleted.

Since the check of the parent element (Foo) occurs before the nested child elements (Bars) are destroyed, Foo will check, then the bars will be destroyed and the user will not be mistaken.

I would add this as a comment, but at the moment there are not enough repetitions

+2
source

Just in case, if someone sees this, it should work on Rails 3. I think add_to_base (using Tony and Jeremy) has been removed, so it should be like this:

 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 
+1
source

Source: https://habr.com/ru/post/1306299/


All Articles