Jake
Jake

Reputation: 967

Rails 3 Change Error Message

I have an error message that appears when my the field for the database :b_name is empty. However, b_name stands for Business Name and I have made the label say that. However, when I get the error message, it says B name cant be blank. Is there any way I can change it so when I get the error it says Business Name can't be blank instead of b_name cant be blank?

Upvotes: 9

Views: 4371

Answers (3)

rogeliog
rogeliog

Reputation: 3692

Yes it is actually really simple.

You should have a file named config/locales/en.yml, if not simply create one. There you can add your own custom names.

en:
  activerecord:
    models:
      order:            "Order"
    attributes:
      order:
        b_name:         "Business Name"

That will replace your b_name for "Business Name"

Your Order model in app/models/order.rb should look like:

class Order < ActiveRecord::Base
  validates :b_name, :presence => true
  .
  . 
  .

Please let me know if it worked :)

Here is an screenshot of my app working fine. Here is an screenshot of my app working

Upvotes: 13

diedthreetimes
diedthreetimes

Reputation: 4115

My guess is you have something like this in your model

validates_presence_of :b_name

If you want to change the message printed when this validation fails you can use the :message option

validates_presence_of :b_name, :message => 'some other message' unfortunately this will still print the field name. The message will be 'B name some other message'

To get around it see this other SO question.

Using Rails validation helpers :message but want it without listing the column name in message

From this post The easiest method is to add a human_attribute_name method like so,

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :b_name => "Business Name"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

Upvotes: 0

s.m.
s.m.

Reputation: 8043

Try using the :message validation option, it's common to all validation methods.

Upvotes: 3

Related Questions