2

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

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)。

任何人都可以帮忙吗?

4

1 回答 1

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 => {...}

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

于 2012-08-15T12:12:15.577 回答