Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change error field name in Rails

I'm wondering if there's a way to change the field name for a validation error it's associated with. For example, if I submit First Name (really fname in the table) without any data, it yells Fname can't be blank.

Is it possible to change this to First Name can't be blank?

like image 329
stewart715 Avatar asked Apr 26 '11 03:04

stewart715


1 Answers

The general practice now-a-days is to edit your locals like so:

# config/locales/en.yml en:   activerecord:     attributes:       user:         fname: "First Name" 

Your error message will now say "First Name can't be..."

For completeness sake, you have another option. Which is to add the following to your User Model:

class User < ActiveRecord::Base    HUMANIZED_ATTRIBUTES = {     :fname => "First Name"   }    def self.human_attribute_name(attr, options = {}) # 'options' wasn't available in Rails 3, and prior versions.     HUMANIZED_ATTRIBUTES[attr.to_sym] || super   end  end 
like image 126
Mike Lewis Avatar answered Oct 03 '22 14:10

Mike Lewis