Rails accepts_nested_attributes_for and validation ... Rails 2.3.11

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 cannot get the unique permission restriction to work when creating a new group only when updating. Here is an example output. Does anyone know a better way to get validation to work with 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 

It is expected. However, if I create a Group with the same permissions_attributes twice, it does not 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!!! 
+4
source share
1 answer
 class Group < AR has_many :permissions accepts_nested_attributes_for :permissions, :allow_destroy => true validates_associated :permissions end 
0
source

Source: https://habr.com/ru/post/1344820/


All Articles