Question

What is the DRY way to translate certain fields?

In my RESTful views, I have some repeating snippets, like this in a show-view:

...
<dt><%= t("activerecord.attributes.user.firstname") %></dt>
<dd><%= @user.firstname %></dd>
...

Now, instead of writing t("activerecord.attributes.user.attr_name") over and over again, I'd like to write only t(:attr_name) (similar to f.label :firstname in the form-views).

Basically, this should not be a problem (at least for the RESTful views), since the I18n module could query the controller method to extrapolate the model name and then just guess the correct translation string.

My question: Did anyone have practical experience with this approach? Could there even be a RubyGem for it? Or: are there pitfalls, I didn't think of?

Was it helpful?

Solution

I seems, ActiveModel::Translation#human_attribute_name does the trick (e.g. <%= User.human_attribute_name :firstname %>).

OTHER TIPS

The recommended way to do this is to put this into a partial (e.g. app/views/user/_form.html.erb or even app/views/user/_user.html.erb), and then precede the name with a leading dot, thus:

<dt><%= t(".firstname") %></dt>
<dd><%= user.firstname %></dd>

More information: examples (from Agile Web Development with Rails); Rails documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top