问题
I am using the following partial to display error messages for most of my models in Rails 3.2.3:
# _error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<h3><%= pluralize(object.errors.count, "error") %>
prohibited this <%= object.class.to_s.underscore.humanize.downcase %> from being saved:</h3>
<p>There were problems with the following fields:</p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
This worked great until I decided to localize my application using I18n
.
I created a new file de.yml
for the German language content which contains this (among many other things):
# de.yml
errors: &errors
format: ! '%{attribute} %{message}'
messages:
blank: muss ausgefüllt werden
template:
body: ! 'Bitte überprüfen Sie die folgenden Felder:'
header:
one: ! 'Konnte %{model} nicht speichern: ein Fehler.'
other: ! 'Konnte %{model} nicht speichern: %{count} Fehler.'
etc. etc. etc.
Now how can I use this content in my error messages?
Especially the line <%= object.class.to_s.underscore.humanize.downcase %>
puzzles me. I tried something like <%= t 'activerecord.errors.template.header', :model => object.model_name.human %>
but without any luck.
Can anybody help?
I read the Rails guide on localization three times already, but I am stuck here.
Thanks for any help!
回答1:
First of all you should set your locale by this:
application.rb
config.i18n.default_locale = :de
Second, your locale file should look like this:
de.yml
de:
activerecord:
models:
order: Заказ
attributes:
order:
link: Ссылка на модель часов
name: Имя
phone: Телефон
accept_message: Комментарий к заказу
decline_message: Причина отказа
finish_message: Комментарий к заказу
errors:
models:
order:
attributes:
link:
blank: не может быть пустой
phone:
invalid: должен содержать только цифры. Пример: 9208003020 или 2716070.
blank: не может быть пустым
name:
blank: не может быть пустым
decline_message:
blank: не может быть пустой
回答2:
OK, I found the answer myself this time, thanks to this thread.
I simply changed my _error_messages.html.rb
partial to:
<% if object.errors.any? %>
<div id="error_explanation">
<h3><%= t('errors.template.header', :model => object.class.model_name.human, :count => object.errors.count) %></h3>
<p><%= t('errors.template.body') %></p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Now it works and I am happy :-)
来源:https://stackoverflow.com/questions/14536518/how-to-localize-a-generic-error-messages-partial-in-rails-3-2-3