问题
I got a Event model that HABTM Categories. The relationship works fine and I can insert/retrieve values from Categories with no problem.
My questions is, is there a way to interzationalize(I18n) the values of this categories.
Category Model
class Category < ActiveRecord::Base
has_and_belongs_to_many :events
end
Event Model
class Event < ActiveRecord::Base
....
has_and_belongs_to_many :categories
....
_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
回答1:
I'm assuming the categories are pretty much fixed (otherwise you wouldn't really be able to do any i18n on them)
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"
......
And if you do for example Category.all.map(&:name)
will result in ["some_category", "some_other_category", ....]
And in your view:
- 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)
来源:https://stackoverflow.com/questions/10101268/rails-3-1-internalization-of-values-from-a-habtm-relationship