2

我已经开始从事一个项目,我之前的人使用 HAML 显示两个选择框,并根据第一个的选择更新第二个。我不明白如何将 HAML 转换为 ERB,所以我只是将 HAML 放在一个部分中。第一个选择框显示正确的值,但第二个不包含任何内容。如何使第一个框使用正确的值更新第二个框?第一个包含状态,然后第二个应该包含基于所选状态的安装。这是我的代码:

搜索视图:

<%= render 'state_installation_select' %>

HAML 部分:

= state_installation_select @states, @installation_options_by_state # ProgramsHelper

程序助手:

def state_installation_select(states, installation_options_by_state)
    haml_tag(:div, class: 'field') do
      haml_concat(label_tag :state, "Please select your state")
      haml_concat(select_tag :state, options_for_select(states), include_blank: true, class: 'state state_installation_select')
    end

    haml_tag(:div, class: 'field') do
      haml_concat(label_tag :installation_id, "Please select your installation")
      haml_concat(select_tag :installation_id, nil, include_blank: true, class: 'installation state_installation_select')
    end
    content_for :domready, %(InstallationSelect.init(#{installation_options_by_state.to_json});).html_safe
  end

程序控制器:

def search_form_for_parents
    @installations = Installation.all
    @states = Installation.states
    @installations_by_state = @installations.group_by(&:state_code)
    @installation_options_by_state = @installations_by_state.each_with_object({}){ |(state,installations), h| h[state] = installations.map{|i| [i.name, i.id]} }
end

程序Javascript:

var InstallationSelect = {
  init: function(installations_for_state){

    $state_select = $('select.state.state_installation_select');

    $state_select.change(function(){
      var state = $(this).val();
      var installations = installations_for_state[state] || [];
      var $installation_select = $(this).parent().parent().find('select.installation.state_installation_select');

      $installation_select.html( InstallationSelect.options_for_select(installations) );
    }).triggerHandler('change');
  },

  options_for_select:function(container){
    var options = jQuery.map(container, function(c){
      return '<option value="' + c[1] + '">' + c[0] + '</option>';
    });

    return options;
  }

};
4

0 回答 0