2011-12-22 42 views
2

我一直在想辦法在類中聲明數組常量,然後在選擇控件中將數組的成員呈現爲分組選項。我使用數組常量的原因是因爲我不希望選項被數據庫模型支持。grouped_collection_select與I18n

這可以在基本意義上完成,而使用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 

結果是:

Grouped collection select control

所以,我已拿出一個合理的解決方案?還是我走了軌道?

謝謝!

回答

0

從沉默的響聲中我收到的問題作爲迴應,我猜測沒有更好的辦法。無論如何,這種方法的工作原理和我堅持下去,直到我發現更好的東西。