validates_uniqueness_of

Hi,

In my user model I validates_uniqueness_of :login.

In my app, users can edit their information. If the user change the name but not the login, the record gets rejected. Of course the login is already used, but by the same user that it is editing his information.

The record should not be rejected right ? Could someone tell me if it is normal that it gets rejected ?

Thanks, Mickael.

So, nobody thinks that validates_uniqueness_of should accept the edition of the same record ? Should I add an on create condition and validate the record "by hand" on edition ? Mickael.

you might need to :scope the contraint: http://api.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M000944

Jeremy: Okay, if it's the only solution, I will do the update validation by hand. Thanks Jeremy. I was hoping Rails was a little bit more "intelligent" and it would detect that we are updating the same record, so it is OK to set the same value as before.

Jemminger: I don't think a scope can help me there. I want to validates the uniqueness of this field on the global scope. Thanks anyway.

Mickael.

I agree that it should be more intelligent. I would think that :except => ‘update’ would lead to inconsistencies unless you added a before update filter that checked this on your own…I think a select count where id != self.id and attrib = attrib would do it. I may be stating the obvious here, but I was quite surprised myself to learn that it behaves this way.

MickTaiwan wrote:

According to the source, this problem should not happen:

547: unless record.new_record?
548: condition_sql << " AND #{record.class.table_name}.#{record.class.primary_key} <> ?"
549: condition_params << record.send(:id)
550: end

I’ll dig in to it next week and see whats happening.

William Pratt wrote:

I played around with this a little, and I was mistaking yesterday. I am seeing the correct behavior on updates with validates_uniqueness_of. If the duplicate is in the record I am updating, the validation passes.

in my asset.rb model:

validates_uniqueness_of :asset_tag, :scope => :company_id

in irb:

a = Asset.find(:first)

a.asset_tag

=> “AS00003”

a.new_record?

=> nil

a.asset_tag = “AS00003”

=> “AS00003”

a.new_record?

=> nil

a.valid?

=> true

William Pratt wrote:

Thanks for the update.

I had implemented a solution "by hand", with an :on=>:create and doing the validation by hand on update.

After seeing the source you just sent, I reverted to the old (and to me "normal") way of doing it, and then it worked. I don't know why it failed earlier.

Sorry for the fuss, and again thank you for the work you've done.

Mickael.