1 分鐘閱讀

版本

Ruby 2.3.1 / Rails 5.0.1

說明

本次實作動態下拉選單。

步驟

1. 建立model

$ rails g model country name
$ rails g model state name country:belongs_to
$ rails g scaffold person name country:belongs_to state:belongs_to 

$ rails db:migrate

2. 建立資料(seed)

(預先準備了兩個csv在根目錄)

# [path] seed.rb
require 'csv'

puts "Importing countries..."
CSV.foreach(Rails.root.join("countries.csv"), headers: true) do |row|
  Country.create! do |country|
    country.id = row[0]
    country.name = row[1]
  end
end

puts "Importing states..."
CSV.foreach(Rails.root.join("states.csv"), headers: true) do |row|
  State.create! do |state|
    state.name = row[0]
    state.country_id = row[2]
  end
end

執行

$ rails db:seed

3. 調整 model

# [path] conutry.rb
class Country < ApplicationRecord
  has_many :state
  has_many :people
end
# [path] state.rb
class State < ApplicationRecord
  belongs_to :country
  has_many :people
end

4. 加入route

# [path] route.rb
Rails.application.routes.draw do
  resources :people
  root 'people#index'
end

可以開啟server來看

$ rails s

5. 調整 people/_form.html.erb

  <div class="field">
    <%= f.label :country_id %>
    <%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
  </div>
  <div class="field">
    <%= f.label :state_id, "State or Province" %>
    <%= f.grouped_collection_select :state_id, Country.order(:name), :states, :name, :id, :name, include_blank: true %>
  </div>

6. 調整people.js

// [path] people.js
jQuery(function() {
  var states;
  $('#person_state_id').parent().hide();
  states = $('#person_state_id').html();
  return $('#person_country_id').change(function() {
    var country, escaped_country, options;
    country = $('#person_country_id :selected').text();
    escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1');
    options = $(states).filter("optgroup[label='" + escaped_country + "']").html();
    if (options) {
      $('#person_state_id').html(options);
      return $('#person_state_id').parent().show();
    } else {
      $('#person_state_id').empty();
      return $('#person_state_id').parent().hide();
    }
  });
});

參考

  1. https://github.com/railscasts/088-dynamic-select-menus-revised
  2. http://railscasts.com/episodes/88-dynamic-select-menus-revised

更新時間:

留言