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.

validates_uniqueness_of fails when primary key value changed

#5117
class Role
  set_primary_key :short_name
  validates_uniqueness_of :name
end

test "validates_uniqueness_of" do
  r = Role.new(:name => "name" )
  r.short_name = "first"
  r.save!

  r.short_name = "second"
  assert r.valid?
  assert_equal 0, r.errors[:name].size
end

The validation fails when it should not.
The query that is generated by uniqueness validation is:
SELECT "roles"."short_name" FROM "roles" WHERE ("roles"."name" = 'name') AND ("roles".short_name <> 'second') LIMIT 1
The query uses the changed, unsaved short_name (primary_key) value which is "second" instead of the previous one ("first") when checking on db for other records that could have the same :name.

This is not nice when someone wants to use natural keys as primary keys.

Reported by Robert Pankowecki · July 15th, 2010 @ 10:27 AM

State: stale
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Subba
    Subba

    even when primary key is natural if you set change the id rails is not resetting
    see below example.

    class Car < ActiveRecord::Base
      validates_uniqueness_of :name
    end
    
    
    ruby-1.8.7-p174 > c = Car.create(:name => "Nissan")
      Car Load (0.4ms)  SELECT "cars"."id" FROM "cars" WHERE ("cars"."name" = 'Nissan') LIMIT 1
      SQL (0.3ms)  INSERT INTO "cars" ("name") VALUES ('Nissan')
     => #<Car id: 2, name: "Nissan"> 
    ruby-1.8.7-p174 > c.id = 3
     => 3 
    ruby-1.8.7-p174 > c.valid?
      Car Load (0.5ms)  SELECT "cars"."id" FROM "cars" WHERE ("cars"."name" = 'Nissan') AND ("cars".id <> 3) LIMIT 1
     => false
    

    July 16th, 2010 @ 09:49 PM

  2. Santiago Pastorino
    Santiago Pastorino
    • State changed from new to open

    This issue has been automatically marked as stale because it has not been commented on for at least three months.

    The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.

    Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.

    February 2nd, 2011 @ 04:35 PM

  3. Santiago Pastorino
    Santiago Pastorino
    • State changed from open to stale

    February 2nd, 2011 @ 04:35 PM