如何创建可翻译的成功通知?
我正在尝试创建一个可翻译的成功通知。该通知将通过成功调用创建和更新操作来调用。
这就是我到目前为止所拥有的:
#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'}") }
问题是这显示了消息:“%{model} 已成功创建。”。我如何让它说:“地点已成功创建。”?
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."?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用 i18n 的插值函数(请参阅 http://guides.rubyonrails.org/i18n.html#插值)执行类似
model_name
返回所创建对象的类名称的操作(请参阅http://api.rubyonrails.org/classes/ActiveModel/Name.html)。在此对象上调用human 返回模型名称的 i18n 翻译(来自范围 activerecord.models.{model_name})
You need to use i18n's interpolation functions (see http://guides.rubyonrails.org/i18n.html#interpolation) do do something like
where
model_name
returns the name of the class of the created object (see http://api.rubyonrails.org/classes/ActiveModel/Name.html). callinghuman
on this object returns the i18n translation of the model name (from the scope activerecord.models.{model_name})您可以简单地编写:(
请注意,您正在将其写入
places_controller.rb
文件中,因此您知道它将是一个被保存的place
,无需@place.class.model_name. human
罗嗦的东西。)这将告诉 i18n 使用哪个
model
的翻译,现在你只需要本地化模型名称,这非常简单并通过添加完成activerecord
中的model
部分,因此您的语言环境 yaml 文件将如下所示:同样,正如您在示例中看到的,您还可以指定属性名称,该属性名称将在表单、错误验证和其他地方很有用。
You can simply write:
(Note that you are writing this in the
places_controller.rb
file, so you know it will be aplace
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 themodel
section within theactiverecord
one, so your locale yaml files will look like: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.