do_Ob
do_Ob

Reputation: 719

How to pass the value of column to the custom error message of validates

I have a model with 2 column, name and answer

How can I pass the value of name to the custom error message of validates of a model.

sample code:

#app/models/sample_model.rb
Class SampleModel < ActiveRecord::Base
    validates :answer, 
                :presence => {:message => "Error name: #{self.name}"}
end

Instead of the value of column name, it shows the name of the model which is SampleModel.

Upvotes: 3

Views: 1559

Answers (1)

Bryan Dimas
Bryan Dimas

Reputation: 1452

To have access to the value of an attribute (column) being validated, you need to use the ActiveModel::Validations class. That class has a validates_each method that you can use to access the values of a record being validated.

#app/models/sample_model.rb
class SampleModel < ActiveRecord::Base
  include ActiveModel::Validations

  attr_accessor :sample_attribute

  validates_each :sample_attribute allow_blank: true do |record, attr, value|
      record.errors.add :base, 'Error name: #{value}' if value.nil?
  end
end

In record.errors.add is where you can customize your message. It takes three parameters attribute, message, and options. In the above, I put :base for the attribute basically to customize further you custom message.

See here for more info on the validates_each method and here for the 'add' method in the Active Model Errors class. Also this section on the Rails Guide will help.

Upvotes: 2

Related Questions