2011-12-22 6 views
2

私は、クラスの配列定数を宣言し、配列のメンバーを選択コントロールのグループ化されたオプションとして提示する方法を考案してきました。私が配列定数を使用している理由は、データベースモデルによってサポートされているオプションを望んでいないからです。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 

の結果は次のとおりです。

Grouped collection select control

だから、私は合理的な解決策が出ていますか?または、私は道から離れた?

ありがとうございます!

答えて

0

返信の沈黙から、私の質問に応答して、私はより良い方法がないと推測しています。とにかく、アプローチは機能し、私は何かを発見するまでそれに固執しています。