Removing "Validation failed" message from Exception return message
rails-activerecord, ruby-on-rails, ruby-on-rails-3, validation
Solution
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.
account = Account.new(:msisdn => user)
unless account.save #
# account.errors will be populated with errors
puts account.errors[:msisdn] # => ['User Already Registered']
end
Alternative using a bang method
account = Account.new(:msisdn => user)
begin
account.save!
rescue Exception
puts account.errors[:msisdn]
end
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)
begin
account = Account.create!(:msisdn => user)
rescue ActiveRecord::RecordInvalid => e
puts e.record.errors[:msisdn] # => ['User Already Registered']
end
Problem
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