ActiveRecord限制关联计数与nested_form gem和accept_nested_attributes,allow_destroy =>真正

时间:2012-08-15 11:45:37

标签: ruby-on-rails validation activerecord nested-attributes

我想将我的关联限制为两个(每个范围之一)。我试过了:

has_many :associations
has_many :associations_with_first_scope, :class_name => 'Association', :conditions => {...}
has_many :associations_with_second_scope, :class_name => 'Association', :conditions => {...}

validates :associations, {:maximum => 4}
validates :associations_with_first_scope, {:maximum => 2}
validates :associations_with_second_scope, {:maximum => 2}

我也尝试过自定义验证器(我也试过了数量,尺寸和长度):

validate :custom_associations_limit

def custom_associations_limit
  error.add(:base, '...') if associations_with_first_scope.size > 2
  error.add(:base, '...') if associations_with_second_scope.size > 2
end

我还尝试将验证放入关联模型中。什么都行不通。我认为我的问题是由使用nested_form gem引起的。当我有四个关联(每种类型两个)的形式,我将删除两个并添加两个,模型认为它有六个关联而不是四个。因为它可能在传递nested_attributes之前进行验证(将allow_destroy设置为true)。

任何人都可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

Rails已经内置了has_one宏。

has_many :associations
has_one :associations_with_first_scope, :class_name => 'Association', :conditions => {...}
has_one :associations_with_second_scope, :class_name => 'Association', :conditions => {...}

唯一的区别是你不会使用复数关联,因为只会有一个。