I have already done some research but didn't managed to find how to localize the attributes for my form object.
Here is the relevant part of my form object model:
class Pledge
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveAttr::Attributes
extend ActiveModel::Naming
attribute :pledge_amount
attribute :reward_id
attribute :message
validates :message, presence: true, length: { maximum: 140 }
validates :reward_id, presence: true
validates :pledge_amount, presence: true
...
end
And my locale file, pledges/en.yml:
en:
activerecord:
models:
pledge: "Pledge"
attributes:
pledge:
pledge_amount: "Pledge Amount"
reward_id: "Reward"
message: "Message"
helpers:
submit:
pledge:
create: "Next Step"
label:
pledge:
pledge_amount: "Enter your pledge amount"
reward_id: "Select your reward"
message: "Write a Support Message"
With this setup I managed to localize successfully the labels on the form, heres a part of the form code:
<%= form_for @pledge do |f| %>
<% if @pledge.errors.any? %>
<div id="error_explanation">
<h2><%= t :not_saved, count: @pledge.errors.count, model: t(:pledge) %></h2>
<ul>
<% @pledge.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
...
<%= f.label :pledge_amount %>
<%= f.text_field :pledge_amount %>
...
<%= f.submit class: "btn btn-lg btn-primary" %>
<% end %>
This renders the :pledge_amount label like: "Enter your pledge amount" in English, and the :submit button as "Next Step", great.
The problem happens when validations fail and I render the form with errors with the code I have under the tag, witch gives me the errors existent in the model but with blank attribute names, like this:
one error prohibited this Pledge from being saved:
- can't be blank
When it was supposed to render:
one error prohibited this Pledge from being saved:
- Pledge Amount can't be blank
If you are curious about this message in particular here's the code for that, shortened:
errors/en.yml
en:
not_saved:
one: "one error prohibited this %{model} from being saved:"
other: "%{count} errors prohibited this %{model} from being saved:"
errors:
format: "%{message}"
activerecord:
errors:
messages:
blank: "%{attribute} can't be blank"
This works for all of my other models, but for this one for some reason it doesn't work, I think I'm using the wrong key on my pledges/en.yml file, as my Pledge model doesn't inherit from ActiveRecord...
Someone know the proper key to achieve this?
Put the translations on activemodel
instead of activerecord
in your yaml:
en:
activemodel:
models:
pledge: "Pledge"
attributes:
pledge:
pledge_amount: "Pledge Amount"
reward_id: "Reward"
message: "Message"
I dug this answer up from comments in an old RailsCast. See comment from Greg Yardley.