【问题标题】:Using carmen gem with rails使用带有导轨的 carmen gem
【发布时间】:2015-04-08 10:56:13
【问题描述】:

我要做的是显示国家/地区的 2 个字母缩写代码,即“美国”。

选择国家后,我需要显示其州或省。 但我有一个问题。

我的代码看起来像

<%= 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。

【问题讨论】:

  • 您的意思是要在 HTML 表单中拥有两个 selects。并且选择一个特定的国家将用该特定国家的子区域填充另一个选择?
  • 是的,我确实需要这个。
  • 但是我不明白为什么助手被命名为“only_us_and_canada”
  • 它只是一个助手的名字。
  • 重新整理思路

标签: ruby rubygems ruby-on-rails-4.1


【解决方案1】:

我已经解决了这个问题:

第 1 步:生成迁移

rails g migration addStateCodeFieldToAccounts state_code:string

第二步:在控制器内部定义一个方法

def subregion_options
    render partial: 'subregion_select'
end

第 3 步:在路由中声明

resources :accounts do
    collection do
      get 'subregion_options'
    end
  end

第四步:在视野中

<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:部分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)
  });

是的,它有效 :) 希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多