Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

uniqueness with accepts_nested_attributes_of

#5923

class Room < ActiveRecord::Base

has_many :objects, :dependent => :destroy, :inverse_of => :room

accepts_nested_attributes_for :objects, :allow_destroy => true

end

class Object < ActiveRecord::Base

belongs_to :room, :inverse_of => :objects

validates :forniture_id, :presence => true, :uniqueness => {:scope => :room_id}

validates :room, :presence => true

end


The "uniqueness" validation doesn't work. When the 'select' is issued, room_id is still NULL, it was not yet set by Rails.

Reported by Ivan · November 5th, 2010 @ 08:36 PM

State: duplicate
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Neeraj Singh
    Neeraj Singh
    • Importance changed from to Low

    Can you elaborate what you mean by when the 'select' is issued?

    Can you show me the full case using console?

    Thanks

    November 6th, 2010 @ 06:59 AM

  2. Ivan
    Ivan

    Sorry, I'd like to say the select 'generated' by Rails to verify if the key record already exists.
    In the example, 'room_id' would be 'nil', because it wasn't set by Rails yet.
    If you look in the log you can observe that SQL generated is:

    SELECT objects.id FROM objects WHERE (objects.forniture_id = 10) AND (objects.room_id IS NULL) LIMIT 1

    So, even if you have 2 'Object' with the same 'forniture_id' being inserted into the same Room, the result would be as it has none.

    Thanks

    November 8th, 2010 @ 11:38 AM

  3. Neeraj Singh
    Neeraj Singh
    • State changed from new to duplicate

    November 10th, 2010 @ 09:12 PM