Rails 3.1,habtm关系的价值内部化? [英] Rails 3.1, internalization of values from a habtm relationship?
问题描述
我得到了一个HABTM类别的事件模型.这种关系可以正常工作,我可以毫无问题地从类别"中插入/检索值.
I got a Event model that HABTM Categories. The relationship works fine and I can insert/retrieve values from Categories with no problem.
我的问题是,有没有一种方法可以对这些类别的值进行interzationalize(I18n).
My questions is, is there a way to interzationalize(I18n) the values of this categories.
类别模型
class Category < ActiveRecord::Base
has_and_belongs_to_many :events
end
事件模型
class Event < ActiveRecord::Base
....
has_and_belongs_to_many :categories
....
_form.html.haml(用于事件)
_form.html.haml (for events)
- Category.all.each do |category|
.field
= check_box_tag "category_ids[]", category.id, @event.category_ids.include?(category.id)
= category.name
推荐答案
我假设类别几乎是固定的(否则您将无法对它们进行任何i18n操作)
I'm assuming the categories are pretty much fixed (otherwise you wouldn't really be able to do any i18n on them)
一种解决方案是将类别存储为键(带有下划线),并为每个键将i18n添加到您的语言环境文件中:
One solution would be to save the categories in the database as keys (with underscores) and for each key add the i18n to your locale files:
en.yml
categories:
some_category: "Some category text"
some_other_category: "Some other category text"
......
如果您这样做,例如Category.all.map(&:name)
将导致["some_category", "some_other_category", ....]
And if you do for example Category.all.map(&:name)
will result in ["some_category", "some_other_category", ....]
在您看来:
- Category.all.each do |category|
.field
= check_box_tag "category_ids[]", category.id, @event.category_ids.include (category.id)
= I18n.t("categories.#{category.name}")
请注意,如果您尝试动态执行此操作,那么这不是一个好的解决方案(如果是这种情况,则需要将翻译存储在数据库中,并且
Note this is not a good solution if you're trying to do this dynamically (if that's the case, you're going to need to store the translations in the database, and this might help)
这篇关于Rails 3.1,habtm关系的价值内部化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!