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
Add two things to "config/locale/en.yml":
en:
  activerecord:
    errors:
      messages:
        record_invalid: "%{errors}"
  errors:
    format: "%{message}"
(or corresponding translation files for whichever languages you happen to support).
Note: this was tested in rails 5, but a quick scan of rails 3 docs makes me think it'll work there too.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With