save! not allowed after validates_uniqueness

Can you please explain why you think the validation should be "skipped"?

Cheers, Nicholas

Hi Nicholas,

Thanks for your response. What I meant was that validation should not compare the object that is being updated against its own existing copy. For example, I am editting an existing object:

   [:aspect => "Aspect-A", :user_id => 5, :third_field => "morning"].

Now, the object is unique in the database according to

   validates_uniqueness_of :aspect, :scope => :user_id

That's all good. However, when I update the object with the following statements:

   self.third_field = "night"    save!

Rails returns an error:

   ActiveRecord::RecordInvalid: Validation failed: Aspect has already been taken

Why? I am just trying to update an existing object, not create a new one that would violate the uniqueness validation.

Thanks.

What code are you using for creating and modifying the object before saving it?

Colin

Hi Colin,

Thanks for asking that question. I had preloaded the database so I didn't have to create a new record. So now I just tried doing that and it wouldn't let me create a new record although the :aspect value I used does not exist at all in the database. Console output is below:

stat0 = Stat.new(:user => user0, :aspect => "aspect0")

=> #<Stat id: nil, user_id: 1000, aspect: "aspect0", . . .>

stat0.save!

ActiveRecord::RecordInvalid: Validation failed: Aspect has already been taken   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/validations.rb:1021:in `save_without_dirty!'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/dirty.rb:87:in `save_without_transactions!'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/transactions.rb:200:in `save!'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/database_statements.rb:136:in `transaction'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/transactions.rb:182:in `transaction'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/transactions.rb:200:in `save!'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/transactions.rb:208:in `rollback_active_record_state!'   from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.2/lib/active_record/transactions.rb:200:in `save!'   from (irb):70

"aspect0" is something I completely made up and does not exist in the database. :user_id 1000 does exist in different rows with different values of :aspect however.