我正在尝试做的是显示国家的2个字母的缩写代码,即'US‘。
选择国家后,我需要显示它的州或省。但我有个问题。
我的代码看起来像这样
<%= f.select :country_code, region_options_for_select(only_us_and_france) %>并在helper中定义:
def only_us_and_france
Carmen::Country.all.select{|c| %w{US FR}.include?(c.code)}
end我使用的是Rails 4.1.0。
发布于 2015-04-09 14:14:49
我已经通过以下方式解决了这个问题:
Step1:生成的迁移
rails g migration addStateCodeFieldToAccounts state_code:stringStep2:在控制器内部定义方法
def subregion_options
render partial: 'subregion_select'
endStep3:在路由中声明
resources :accounts do
collection do
get 'subregion_options'
end
endStep4:在视图中
<div class="input-control select state_input" data-role="input-control">
<%= f.select :country, region_options_for_select(only_us_and_france) %>
</div>
<div class="input-control select state_input" data-role="input-control">
<%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>
</div>Step5: Make partial subregion_select
<div id="account_state_code_wrapper">
<% parent_region ||= params[:parent_region] %>
<% country = Carmen::Country.coded(parent_region) %>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state_code, parent_region) %>
<% else %>
<%= text_field(:order, :state_code) %>
<% end %>
</div>Step6:在我的js文件中写下这个
$('select#account_detail_country').change(function(){
selectWrapper = $('#account_state_code_wrapper')
countryCode = $(this).val()
url = "/account_details/subregion_options?parent_region="+countryCode
console.log(url)
selectWrapper.load(url)
});是的,它起作用了:)希望这会对你有所帮助。
https://stackoverflow.com/questions/29512717
复制相似问题