私は、クラスの配列定数を宣言し、配列のメンバーを選択コントロールのグループ化されたオプションとして提示する方法を考案してきました。私が配列定数を使用している理由は、データベースモデルによってサポートされているオプションを望んでいないからです。grouped_collection_select with I18n
これは基本的な意味で、grouped_collection_selectビューヘルパーを使用するほうが簡単です。それほど単純ではないのは、元の配列エントリをバックグラウンドで保持しながら、このローカライズ可能なものにすることです。言い換えれば、どのロケールでもオプションを表示したいのですが、フォームに元の配列値を送信したいのです。
とにかく、私は解決策を考案しましたが、それはあまりにも複雑です。私の質問です:良い方法がありますか?複雑な解決策が必要か、もっと簡単な解決策を見落としてしまったのですか?
私の解決策は、人為的な例を使って説明します。のは、私のモデルクラスを見てみましょう:以下YMLで
<%= f.grouped_collection_select :character_type, CharacterDefinition.TYPES, 'values[0]', 'keys[0].translate', :to_s, :translate %>
:ように見える
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声明:
を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クラスが翻訳を行います
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
の結果は次のとおりです。
だから、私は合理的な解決策が出ていますか?または、私は道から離れた?
ありがとうございます!