ruby on rails - How to pass the value of column to the custom error message of validates -


i have model 2 column, name , answer

how can pass value of name custom error message of validates of model.

sample code:

#app/models/sample_model.rb class samplemodel < activerecord::base     validates :answer,                  :presence => {:message => "error name: #{self.name}"} end 

instead of value of column name, shows name of model samplemodel.

to have access value of attribute (column) being validated, need use activemodel::validations class. class has validates_each method can use access values of 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 |record, attr, value|       record.errors.add :base, 'error name: #{value}' if value.nil?   end end 

in record.errors.add can customize message. takes 3 parameters attribute, message, , options. in above, put :base attribute customize further custom message.

see here more info on validates_each method , here 'add' method in active model errors class. this section on rails guide help.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -