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

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

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

android - How to create dynamically Fragment pager adapter -