你如何用另一个的结果过滤一个`collection_select`?

时间:2014-11-08 22:04:55

标签: ruby-on-rails ruby-on-rails-3

我有以下代码块。我的数据库设置为每个州has_many县的位置。

  <div class="field">
    <%= collection_select(:location, :state, State.all, :id, :name) %>
  </div>

  <div class="field">
    <%= collection_select(:location, :county, County.all, :id, :name) %>
  </div>

如何根据第一个collection_select的选择过滤第二个collection_select?例如,如果使用选择New Jersey作为第一个字段,那么第二个字段不应该选择加州中的县。

1 个答案:

答案 0 :(得分:0)

  1. 创建一个Utilities控制器来处理请求
  2. 添加此方法以获取州的县

    def county_select
      @state = State.find(params[:state_id])
      @counties_html = render_to_string :partial => 'counties_select',locals:{counties:  @state.counties}
      render :json => { :counties => @counties_html }
    end
    
  3. 添加路线

  4.     controller :utilities do
          get "/utilities/county_select" => :county_select
        end
    
    1. 创建&#34; counties_select&#34;部分

        = collection_select(:location, :county, counties, :id, :name)
      
    2. 在更改第一个选择框

      时添加ajax
        $("body").on "change", "#state_select", ->
          $.ajax
            url: "/utilities/county_select"
            type: "GET"
            dataType: "json"
            data:
              parent_id: $(this).val()
      
      
        success: (result) ->
            $("#county_select").html result.counties
          return
      
    3. 添加ID&#34; state_select&#34;到第一个选择和&#34; county_select&#34;到第二个