【发布时间】:2011-12-22 03:27:44
【问题描述】:
我一直在尝试想出一种方法来在类中声明数组常量,然后在选择控件中将数组的成员作为分组选项呈现。我使用数组常量的原因是我不希望数据库模型支持这些选项。
这可以使用 grouped_collection_select 视图助手在基本意义上相当容易地完成。不那么简单的是使其可本地化,同时将原始数组条目保留在后台。换句话说,我想在任何语言环境中显示选项,但我希望表单提交原始数组值。
无论如何,我想出了一个解决方案,但它似乎过于复杂。我的问题是:有没有更好的方法?是否需要一个复杂的解决方案,还是我忽略了一个更简单的解决方案?
我将使用一个人为的示例来解释我的解决方案。让我们从我的模型类开始:
class CharacterDefinition < ActiveRecord::Base
HOBBITS = %w[bilbo frodo sam merry pippin]
DWARVES = %w[gimli gloin oin thorin]
@@TYPES = nil
def CharacterDefinition.TYPES
if @@TYPES.nil?
hobbits = TranslatableString.new('hobbits', 'character_definition')
dwarves = TranslatableString.new('dwarves', 'character_definition')
@@TYPES = [
{ hobbits => HOBBITS.map {|c| TranslatableString.new(c, 'character_definition')} },
{ dwarves => DWARVES.map {|c| TranslatableString.new(c, 'character_definition')} }
]
end
@@TYPES
end
end
TranslatableString 类进行翻译:
class TranslatableString
def initialize(string, scope = nil)
@string = string;
@scope = scope
end
def to_s
@string
end
def translate
I18n.t @string, :scope => @scope, :default => @string
end
end
查看erb语句如下:
<%= f.grouped_collection_select :character_type, CharacterDefinition.TYPES, 'values[0]', 'keys[0].translate', :to_s, :translate %>
使用以下 yml:
en:
character_definition:
hobbits: Hobbits of the Shire
bilbo: Bilbo Baggins
frodo: Frodo Baggins
sam: Samwise Gamgee
merry: Meriadoc Brandybuck
pippin: Peregrin Took
dwarves: Durin's Folk
gimli: Gimli, son of Glóin
gloin: Glóin, son of Gróin
oin: Óin, son of Gróin
thorin: Thorin Oakenshield, son of Thráin
结果是:
那么,我想出一个合理的解决方案了吗?还是我走偏了?
谢谢!
【问题讨论】:
标签: ruby-on-rails ruby