4

I have two models

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

I can't seem to get the unique constraint on permissions to work when creating a new group, only on update. Here's a sample output. Does anyone know the best way to get validation to work on nested attributes and unique constraints?

sample output

> 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

That is expected. However if I create the Group with the same permissions_attributes twice, it doesn't invalidate:

> 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!!!
brad
  • 31,987
  • 28
  • 102
  • 155
  • It's most likely because each permission is being saved within the same transaction (of the parent). From the rails docs: "All changes to models, including the destruction of those marked for destruction, are saved and destroyed automatically and atomically when the parent model is saved. This happens inside the transaction initiated by the parents save method." My guess is the db lookup for uniqueness is passing since the objects aren't truly stored yet. – mnelson Mar 22 '11 at 19:05
  • Did you solve this problem? I'm having the same thing http://stackoverflow.com/questions/8111424/uniqueness-validation-using-has-many-through-association – Amree Nov 14 '11 at 01:54
  • sorry, long forgot about this one, haven't looked into the final solution as I moved on to other things. – brad Nov 14 '11 at 03:30

1 Answers1

0
class Group < AR
  has_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true
  validates_associated :permissions
end
fl00r
  • 82,987
  • 33
  • 217
  • 237