验证嵌套属性的数量

Dam*_*IEU 4 ruby ruby-on-rails nested-attributes

我有一个嵌套属性的模型:

class Foo < ActiveRecord::Base
    has_many :bar
    accepts_nested_attributes_for  :bar
end
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是我想确保每一个Foo,我至少有两个Bar.我无法访问bar_attributes我的验证,所以我似乎无法验证它.

有没有干净的方法呢?

Ton*_*not 7

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
Run Code Online (Sandbox Code Playgroud)

控制器将负责构建/更新条形图,因此您只需要查看是否有足够的条形图.