ShayDavidson
ShayDavidson

Reputation: 781

How to validate uniqueness of nested models in the scope of their parent model 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 an 'Item' model:

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

I want to validate the uniqueness of the :some_attr attribute of all the Items which belongs to a certain room.

When I try to validate the items, I get this error:

TypeError (Cannot visit Room)

I cannot set the scope of the validation to be :room_id since the items are not saved yet so the id is nil. I also want to prevent using custom validators in the 'Room' model.

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

Upvotes: 4

Views: 1369

Answers (1)

HargrimmTheBleak
HargrimmTheBleak

Reputation: 2167

I don't see anything wrong with how you're using inverse_of.

As for the problem, in a similar situation I ended up forcing a uniqueness constraint in a migration, like so

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

This is in addition to the AR-level validation

validates_uniqueness_of :some_attr, :scope => :room_id

(I'm not sure if it's valid to use the association name as a scope, won't the DB adapter raise an exception when trying to refer to the non-existent room column in a query?)

Upvotes: 2

Related Questions