LoginSignup
12
8

More than 5 years have passed since last update.

世界の国とその地域名を入手する方法

Last updated at Posted at 2015-01-18

世界の国とその地域名を入手する方法

Userモデルを使ってユーザーの出身国と州を入れてみる。

1. carmen-railsのgemを加える

Gemfile
gem 'carmen-rails'

保存したらbundle installする。

2.country_codeとstate_codeのカラムをUserに作成する
rails g migration AddCountryStateToUser

db/migration/2015xxxxxxxxx_add_country_state_to_user.rb
class AddCountryStateToUser < ActiveRecord::Migration
  def change
    add_column :users, :country_code, :string
    add_column :users, :state_code, :string
  end
end

3.入力フォームを作っていく

users/_form.html.erb
<div class="field">
  <%= f.label :country_code %><br />
  <%= f.country_select :country_code, prompt: 'Please select a country' %>
</div>
<div class="field">
  <%= f.label :state_code %><br />
  <%= render partial: 'subregion_select', locals: {parent_region: f.object.country_code} %>
</div>

4.ビューにpartialの行き先を作成してあげる

users/_subregion_select.html.erb
<div id="user_state_code_wrapper">
  <% parent_region ||= params[:parent_region] %>
  <% country = Carmen::Country.coded(parent_region)  unless parent_region.nil? %>

  <% if country.nil? %>
    <em>Please select a country above</em>
  <% elsif country.subregions? %>
    <%= subregion_select(:user, :state_code, parent_region) %>
  <% else %>
    <%= text_field(:user, :state_code) %>
  <% end %>
</div>

5.javascriptに国名を入力した後に州を選択できるようコードを書いてあげる

assets/javascripts/users.js.coffee
$ ->
  $('select#user_country_code').change (event) ->
    select_wrapper = $('#user_state_code_wrapper')

    $('select', select_wrapper).attr('disabled', true)

    country_code = $(this).val()

    url = "/users/subregion_options?parent_region=#{country_code}"
    select_wrapper.load(url)

6.ルートにユーザーの下にsubregionを加えてあげる

config/routes
resources :users do
    collection do
      get :subregion_options
    end
end

7.ユーザーコントローラーにsubregionを加えてあげる

controllers/users_controller.rb
  def subregion_options
    render partial: 'subregion_select'
  end

完成!!!!

参考サイト
https://github.com/jim/carmen-demo-app/

12
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8