2013-09-27 96 views
1

我是Rails的新手,我試圖找出一個更好的方法:使用從YAML文件讀取的Rake任務將一些種子數據加載到我的數據庫中。如何避免多個if/else

Template.YAML:

- file_name:  Template1 
    description:  temp1 
    required_fields: address 

- file_name:  Template2 
    description:  temp2 
    required_fields: user_id,user_name 

- file_name:  Template3 
    description:  temp3 
    required_fields: user_id,address 

在我看來,我有一個下拉,用戶可以選擇一個模板加載,並根據他選擇的模板,我需要顯示的文本框中獲取必需的字段以運行模板。

Template.html.slim:

dt 
label for="template_name" Select The Template To Run 
dd 
= select_tag :template_name,options_for_select(@template_seed_data_array.insert(0, "Please select the template")), :onchange => "Template.toggleRequiredFields(); return false" 

#user_id style="display:none" 
dt 
    label for="user_id" Enter User Id 
dd 
    = text_field_tag :user_id, @template_library[:user_id] 

#user_name style="display:none" 
dt 
    label for="user_name" Enter user name 
dd 
    = text_field_tag :user_name, @template_library[:user_name] 
. 
. 
. 

在我coffescript,我做了一堆的if/else隱藏和顯示這些文本框這取決於用戶選擇。

Template.coffee:

​​

隨着時間的推移,模​​板的數量變得更高和的if/else邏輯變得混亂。當用戶選擇模板時,是否有更好的方式來做隱藏/顯示切換?

回答

1

如果您將Template.YAML文件作爲JSON公開給客戶端,這應該很容易。

在JavaScript代碼添加模板數據的JSON轉儲的觀點:

:javascript 
    var templates = #{@templates.to_json}; 

然後寫一些代碼,從中讀取數據:

:coffeescript 
    template = null 
    templateName = $('#template_name').val() 

    # Find the proper template configuration 
    for templateConfig in templates 
    if templateName == template.file_name 
     template = templateConfig # found it! 

    # Hide all fields. 
    $('form input').hide() # or whatever selects everything you want to hide 

    # Show just the fields we need. 
    for fieldID in template.required_fields 
    $("##{ fieldID }").show() 

從這裏你可以添加幾十個條目到你的模板配置文件,或者改變顯示的字段,你根本不需要改變代碼。

+0

謝謝你的方法真棒。我正在考慮使用data-attribute來存儲與該文本字段相關聯的文件名。你對這種方法的想法? –

+1

聽起來好像不會很好。如果你有很多模板,這些數據屬性可能會變得很長或很多。在這種情況下,我認爲讓JS中的數據比HTML中的數據更有意義。 –

+0

很酷。非常感謝。 –