我在DB,国家和州有2个表。现在,当我根据选择选择国家时,它必须显示状态。
用于.rhtml文件中的国家/地区选择我正在使用如下:
<%= select_tag "User[country_id]", options_for_select(Country.all.collect{|x| [x.country,x.id]})%>
现在基于以上选择,我需要选择状态。
答案 0 :(得分:0)
查看:
<%= select_tag
:country_select, # name of selectbox
options_from_collection_for_select(@myrecords, "id", "name"), # your options for this select box
:'data-remote' => 'true', # important for UJS
:'data-url' => url_for(:controller => 'MyController', :action => 'getdata'), # we get the data from here!
:'data-type' => 'json' # tell jQuery to parse the response as JSON!
%>
<%= select_tag
:state_select, # name of selectbox
"<option>Please select something from country select!</option>"
%>
控制器:
class MyController < ApplicationController
def getdata
# this contains what has been selected in the first select box
@data_from_country_select = params[:country_select]
# we get the data for selectbox 2
@data_for_state_select = MyModel.where(:some_id => @data_from_country_select).all
# render an array in JSON containing arrays like:
# [[:id1, :name1], [:id2, :name2]]
render :json => @data_for_state_select.map{|c| [c.id, c.name]}
end
end
使用Javascript:
$(document).ready(function() {
// #country_select is the id of our first select box, if the ajax request has been successful,
// an ajax:success event is triggered.
$('#country_select').live('ajax:success', function(evt, data, status, xhr) {
// get second selectbox by its id
var selectbox2 = $('#state_select');
// empty it
selectbox2.empty();
// we got a JSON array in data, iterate through it
$.each(data, function(index, value) {
// append an option
var opt = $('<option/>');
// value is an array: [:id, :name]
opt.attr('value', value[0]);
// set text
opt.text(value[1]);
// append to select
opt.appendTo(selectbox2);
});
});
});
答案 1 :(得分:0)
我个人从未尝试过这种方式,请在国家/地区下拉列表中尝试此代码。
"f.select_tag :state, State.where(country_id: c.id)"
<div class="field">
<%= f.label :country %><br>
<%= f.select :country_id, Country.all.map {|c| [c.name, c.id] }, {prompt:"Choose Country"} %>
</div>
答案 2 :(得分:0)
您需要使用qtyElem
来获取更新的productElem
,如下所示:
ajax
您必须向states
控制器添加#config/routes.rb
resources :countries do
get :state, on: :member #-> url.com/countries/:country_id/states/
end
操作:
states
这将允许您在更改countries
的值时向此控制器发送ajax请求:
#app/controllers/countries_controller.rb
class CountriesController < ApplicationController
def states
@country = Country.find params[:country_id]
@states = @country.states
respond_to do |format|
format.json { render json: @states.to_json }
end
end
end
-
您还需要确保您的表单格式正确。
具体来说,您需要使用select
代替#app/assets/javascripts/application.js
$(document).on("change", "#countries", function(e){
url = "countries/" + $(this).val() + "/states";
$.get(url, function(data){
$.each(data,function(key, value){
$("#states").find('option').remove().end();
$("#states").append('<option value=' + key + '>' + value + '</option>');
});
}, "json")
});
:
form_for