Pawan Rawat
Pawan Rawat

Reputation: 525

Activerecord uniqueness validation ruby on rails 4.2

I just started trying my hands on Ruby on rails . i have created a mode states and want that every state name must remain unique so i used

uniqueness: true

as per http://guides.rubyonrails.org/active_record_validations.html . As the above document says that the validation is invoked automatically when object.save is called. but When i try to save the objects with same state_name value , no exception is thrown and the record is saved. Can one please help where i am doing it wrong.

Model code

class State < ActiveRecord::Base
  acts_as_paranoid
  validates_presence_of :state_name ,uniqueness: true
end

Controller code

def create
 @stateName = params[:stateName];
 @state = State.new();
 @state.state_name=@stateName;
 if(@state.save())
   resp = { :message => "success" }
 else
   resp = { :message => "fail" }
 end

 respond_to do |format|
   format.json  { render :json => resp } 
 end
end

Thanks in advance for helping!

Upvotes: 0

Views: 370

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

If you want uniqueness check, change

validates_presence_of :state_name ,uniqueness: true

to

validates :state_name, uniqueness: true

If you want uniqueness and presence check both, use

validates :state_name, uniqueness: true, presence: true

An alternate syntax is shown below, however, syntax shown above should be preferred

validates_uniqueness_of :fname
validates_presence_of :fname

Also, as per documentation, please note following with respect to usage of uniqueness: true

It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index on both columns in your database.

The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.

What this means is that it is possible that if multiple users are trying to save records concurrently, there is a possibility records with duplicate state_name can get created as each save is happening on different thread

Upvotes: 2

Related Questions