Reputation: 451
I am trying to create a translatable successful notice. This notice would be called by a successful call of the create and update actions.
This is what I have so far:
#config/locales/en.yml
activerecord:
models:
place: "Place"
successful:
messages:
created: "%{model} was successfully created."
updated: "%{model} was successfully updated."
#app/controllers/places_controller.rb
def create
...
format.html { redirect_to(@place, :notice => "#{t 'activerecord.successful.messages.created'}") }
The problem is that this shows the message: "%{model} was successfully created.". How do I get it to say: "Place was successfully created."?
Upvotes: 3
Views: 3210
Reputation: 3304
You can simply write:
format.html do
redirect_to(
@place,
notice: t('activerecord.successful.messages.created', model: :place
)
end
(Note that you are writing this in the places_controller.rb
file, so you know it will be a place
being saved, no need for @place.class.model_name.human
wordy stuff.)
This will tell the i18n the translation of which model
to use, now you just need to localize the model names, which is very simple and done by adding the model
section within the activerecord
one, so your locale yaml files will look like:
activerecord:
successful:
messages:
created:
enqueued: "La creazione del %{model} è stata messa in coda con successo"
error_header_message:
one: Un errore ha proibito il salvataggio di questo %{model}
other: "%{count} errori hanno proibito il salvataggio di questo %{model}"
models:
article: articolo
attributes:
article:
user_id: Autore
title: Titolo
published: Pubblicato
text: Testo
Similarly, as you can see in the example, you can specify also attribute names which is going to be useful in forms, error validations and other places.
Upvotes: 0
Reputation: 4136
You need to use i18n's interpolation functions (see http://guides.rubyonrails.org/i18n.html#interpolation) do do something like
t('activerecord.successful.messages.created', :model => @my_newly_saved_object.class.model_name.human)
where model_name
returns the name of the class of the created object (see http://api.rubyonrails.org/classes/ActiveModel/Name.html). calling human
on this object returns the i18n translation of the model name (from the scope activerecord.models.{model_name})
Upvotes: 10