“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

Customise attribute names of ActiveRecord objects

Ran into a problem where by the name of the field in our database doesn’t properly reflect the human name of the attribute.

e.g. User#some_id

[12] pry(main)> User.human_attribute_name :some_id
=> "Some"
[13] pry(main)> user = User.new
=> #<User id: nil, some_id: nil>
[14] pry(main)> user.errors.full_messages
=> ["Some should be valid"]

So ‘Some’ is a bit meaningless. But we can change this in the i18n config files like so.

en:
  activerecord:
    attributes:
      user:
        some_id: Something much more awesome
</pre></code>

And then you get this....

<pre><code>
[17] pry(main)> User.human_attribute_name :some_id
=> "Something much more awesome"
[18] pry(main)> user = User.new
=> #<User id: nil, some_id: nil>
[10] pry(main)> user.errors.full_messages
=> ["Something much more awesome should be valid"]

Sweet!