I have an ActiveRecord model Account :
class Account < ActiveRecord::Base
attr_accessible :msisdn
validates_uniqueness_of :msisdn, :on => :create,
:message => "User Already Registered ."
end
And I have a controller which try to create an account :
begin
account = Account.create!(:msisdn => user)
rescue Exception => e
$LOG.error "Account #{user} : --> #{e.message}"
end
Now the e.message always return : Validation failed: Msisdn User Already Registered, how am I supposed just to get just the message alone like User Already Registered. please note that I’m not using views at all, I want to use it from controller, and I’m using Rails 3.
Thanks in advance
When valid? is called on any model (which happens from create/save/update_attributes) it populates an errors object on the model.
Of course if you use a bang method (create!) then the assignment will never happen, so use a non bang method instead.See 3rd code snippet.Alternative using a bang method
Edit:
Another alternative after looking at the rails api docs is to get the record from the exception as it stores a copy. This makes my original statement false.
ActiveRecord::RecordInvalid
(github)