Vimalraj Selvam
Vimalraj Selvam

Reputation: 2245

Rails 3 validates_uniqueness_of works in an unexpected way

I'm new to RoR. I'm facing a problem when using validates_uniqueness_of. I've a table with 3 columns:

name      || father_name || dob
Vimal Raj || Selvam      || 1985-08-30

I've a code in my model like this:

class Candidate < ActiveRecord::Base
   attr_accessible :dob, :father_name, :name
   validates_uniqueness_of :name, scope: [:father_name, :dob], case_sensitive: false,
                           message: ": %{value} already present in the database!!!"
   before_save :capitalize_name, :capitalize_father_name

   private

   def capitalize_name
      self.name.capitalize!
   end

   def capitalize_father_name
      self.father_name.capitalize!
   end
end

It throws error as expected when I insert => "vimal raj, Selvam, 1985-08-30" But it is accepting the following data => "Vimal Raj, selvam, 1985-08-30" . I was expecting it will throw an error, but unexpectedly it accepts the record and inserts into the db as a new record.

Please help me on how to solve this.

Upvotes: 0

Views: 91

Answers (2)

Rails Guy
Rails Guy

Reputation: 3866

If you want a one-liner solution, please try this :

before_validation lambda {self.name.capitalize!; self.father_name.capitalize!}

Hope, it will help.

Upvotes: 2

bratsche
bratsche

Reputation: 2674

I think the case_sensitivity is only matching on name, not on father_name. I would try changing before_save to before_validation so that both name and father_name are consistently the same capitalization when your validation is evaluated.

Upvotes: 1

Related Questions