验证嵌套属性的数量 [英] Validate number of nested attributes

查看:60
本文介绍了验证嵌套属性的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a model with nested attributes :

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

工作正常.但是,我想确保每个Foo至少有两个Bar. 我无法在验证中访问bar_attributes,因此似乎无法验证它.

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.

有什么清洁的方法吗?

推荐答案

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.

这篇关于验证嵌套属性的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆