【问题标题】:ActiveRecord limit associations count with nested_form gem and accept_nested_attributes, allow_destroy => trueActiveRecord 限制关联计数与 nested_form gem 和 accept_nested_attributes, allow_destroy => true
【发布时间】:2012-08-15 11:45:37
【问题描述】:

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

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

有人可以帮忙吗?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 我知道。但是现在限制一个人是暂时的。很快就会变成纯粹的 has_many 了。我需要在我的表单中动态添加结束删除关联。同样的问题是最多 4 个,并将范围限制为 2 个。
  • 为什么不从 has_one 开始,在需要时将其更改为 has_many?看来你把问题复杂化了。
  • has_many 我需要它。我在本地测试它。假设我真的需要最多 4 个,每个范围最多 2 个。我将更新我的问题。
  • 如果你需要限制一个以外的东西,你应该使用has_many through并使用join模型来做验证。
  • 当您不使用nested_form 动态表单时,为什么这种方法有效?而且我认为没有区别。我将只使用相同的方法,但多了一个模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
相关资源
最近更新 更多