Matt Grande
Matt Grande

Reputation: 12157

ActiveRecord Validations: Display something other than the column name

I assume this is really easy, and I'm missing something obvious. I'm connecting to a legacy database that has column dblOrderQty. I'm validating it thusly:

validates_numericality_of :dblOrderQty, :greater_than => 0

This, of course, presents "Dblorderqty must be greater than 0". I'd much rather have that say "Quantity must be greater than 0," but I can't find a way to modify the column name in the message.

Upvotes: 0

Views: 360

Answers (4)

eremite
eremite

Reputation: 1916

I think it'd be cleaner to use localization (as Larry K implied) by adding the following to config/locales/en.yml:

en:
  activerecord:
    attributes:
      model_name:
        dblOrderQty: "Quantity"

I'm not sure if the CamelCase will confuse it or not.

Upvotes: 2

Larry K
Larry K

Reputation: 49114

I use the error_messages_for plugin by Bob Silva. http://agilewebdevelopment.com/plugins/enhanced_activerecord_errors

It includes ability to pass in a hash to change the names of some or all of the model's attributes in the error message. This is done in the view (or a helper). Over-writing the attribute names is also important for localized apps.

Upvotes: 0

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

Not sure if this is best way, but it works :)

class ModelName < ActiveRecord::Base
  HUMANIZED_ATTRIBUTES = {
    :dblOrderQty => "Order Quantity"
  }

  validates_numericality_of :dblOrderQty, :greater_than => 0

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

Upvotes: 1

Matthew
Matthew

Reputation: 923

I haven't tested this but you could possibly overwrite your default attribute accessor in your model like this

def quantity
  read_attribute(:dblOrderQty)
end

And then refer to the overwritten attribute. As alway, refer to the docs

Upvotes: 1

Related Questions