Validate number of nested attributes

删除回忆录丶 提交于 2019-12-01 18:58:20
Tony Fontenot
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.

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!