rails accepts_nested_attributes_for和validations ... Rails 2.3.11

时间:2011-03-22 18:46:37

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

我有两个型号

class Group < AR
  has_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true
end

class Permission < AR
  validates_uniqueness_of :action, :scope => [:role]
end

在创建新组时,我似乎无法获得对权限的唯一约束,仅在更新时。这是一个示例输出。有没有人知道获得验证以处理嵌套属性和唯一约束的最佳方法?

示例输出

> g = Group.create(:permissions_attributes => [{:role => 'admin', :action => 'one'}])
> # Now add the same permissions, should not be valid
> g.permissions_attributes = [{:role => 'admin', :action => 'one'}]
> g.valid?  # => false

这是预期的。但是,如果我使用相同的permissions_attributes创建两次组,则不会使其无效:

> g = Group.new(:permissions_attributes => [{:role => 'admin', :action => 'one'}, {:role => 'admin', :action => 'one'}]
> g.valid?  # => true        BUT THIS SHOULD BE FALSE!!
> g.save # => true           Oh Nos!!!

1 个答案:

答案 0 :(得分:0)

class Group < AR
  has_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true
  validates_associated :permissions
end