This project is archived and is in readonly mode.
validates_uniqueness_of fails when primary key value changed
Reported by Robert Pankowecki | July 15th, 2010 @ 10:27 AM
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.
Comments and changes to this ticket
-
Subba July 16th, 2010 @ 09:49 PM
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
-
Santiago Pastorino February 2nd, 2011 @ 04:35 PM
- 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.
-
Santiago Pastorino February 2nd, 2011 @ 04:35 PM
- State changed from open to stale
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>