2

This seems like a really simple question -- when I'm using form_for or fields_for helpers to generate markup from my models, how can I modify my model to customize the string that appears for a particular attribute?

More or less the same question was asked before[1], but the answer was 'internationalize', and that's not what I'm trying to do, I just want to override one or two humanized attribute names.

Community
  • 1
  • 1
kdt
  • 27,905
  • 33
  • 92
  • 139
  • possible duplicate of [Custom model attribute (column name) title in Ruby on Rails](http://stackoverflow.com/questions/2042841/custom-model-attribute-column-name-title-in-ruby-on-rails) – bensiu Oct 18 '12 at 01:43

2 Answers2

4

Maybe you'll be able to override human_attribute_name in your model along the lines of (not tested)

def self.human_attribute_name(*args)
  if args[0].to_s == "my_attribute"
    return "My Attribute"
  end
  super
end

This value will be used in the labels unless you have corresponding translations, which have a higher priority.

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
  • 2
    Hey! I said that already :-) More usefully, you probably meant `def self.human_attribute_name` since the method is called on the AR class directly by ActionView. – noodl Jan 21 '11 at 13:26
3

You could override human_attribute_name in your AR class. See this mailing list post

noodl
  • 17,143
  • 3
  • 57
  • 55
  • Ah-ha -- this wasn't work for me when I used `<%= fields_for :my_model` but it does work when I do `<% fields_for MyModel.new` -- actionpack is looking for an actual instance to then look up the class and call the human_attribute_name class method. – kdt Jan 21 '11 at 20:35