我有以下代码块。我的数据库设置为每个州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作为第一个字段,那么第二个字段不应该选择加州中的县。
答案 0 :(得分:0)
添加此方法以获取州的县
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
添加路线
controller :utilities do get "/utilities/county_select" => :county_select end
创建&#34; counties_select&#34;部分
= collection_select(:location, :county, counties, :id, :name)
在更改第一个选择框
时添加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
添加ID&#34; state_select&#34;到第一个选择和&#34; county_select&#34;到第二个