validation - How to validate uniqueness of nested models in the scope of their parent model in Rails 3.2? -


here example of problem.

i have 'room' model:

class room < activerecord::base    has_many :items, :inverse_of => :room    accepts_nested_attributes_for :items end 

and have 'item' model:

class item < activerecord::base    belongs_to :room, :inverse_of => :items    validates :some_attr, :uniqueness => { :scope => :room} end 

i want validate uniqueness of :some_attr attribute of items belongs room.

when try validate items, error:

typeerror (cannot visit room) 

i cannot set scope of validation :room_id since items not saved yet id nil. want prevent using custom validators in 'room' model.

is there clean way in rails? wonder if set :inverse_of option correctly...

i don't see wrong how you're using inverse_of.

as problem, in similar situation ended forcing uniqueness constraint in migration, so

add_index :items, [ :room_id, :some_attr ], :unique => true 

this in addition ar-level validation

validates_uniqueness_of :some_attr, :scope => :room_id 

(i'm not sure if it's valid use association name scope, won't db adapter raise exception when trying refer non-existent room column in query?)


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -