Validate number of nested attributes

2019-02-18 01:03发布

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 ?

3条回答
萌系小妹纸
2楼-- · 2019-02-18 01:41

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
查看更多
乱世女痞
3楼-- · 2019-02-18 01:52

Tony's answer actually won't handle the case where an existing Foo's bars are deleted.

Since validation of the parent (Foo) happens before the nested children (Bars) are destroyed, Foo will pass validation, then the bars will be destroyed and there will be no errors presented to the user.

I'd add this as a comment but as of now don't have enough reps

查看更多
疯言疯语
4楼-- · 2019-02-18 01:56
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.

查看更多
登录 后发表回答