How to check the uniqueness of nested models in their parent model area in Rails 3.2?

Here is an example of my problem.

I have a Room model:

class Room < ActiveRecord::Base has_many :items, :inverse_of => :room accepts_nested_attributes_for :items end 

And I have a "Item" model:

 class Item < ActiveRecord::Base belongs_to :room, :inverse_of => :items validates :some_attr, :uniqueness => { :scope => :room} end 

I want to check the uniqueness of the attribute: some_attr of all elements belonging to a particular room.

When I try to check the elements, I get this error:

 TypeError (Cannot visit Room) 

I cannot set the scope of the check: room_id, because the elements have not been saved yet, so id is zero. I also want to prevent the use of custom validators in the Room model.

Is there any clean way to do this in Rails? I also wonder if I set the option correctly: inverse_of ...

+4
source share
1 answer

I see nothing wrong with how you use inverse_of .

As for the problem, in this situation, I was forced to limit the uniqueness of migration, for example

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

This is an addition to checking the AR level.

 validates_uniqueness_of :some_attr, :scope => :room_id 

(I'm not sure if using the association name as the scope is correct, will the database adapter throw an exception when trying to refer to a nonexistent room column in the query?)

+2
source

All Articles