programing tip

Rails Select Drop Down for States?

itbloger 2020. 10. 28. 07:49
반응형

Rails Select Drop Down for States?


레일에 대한 기능이 이미 내장되어있어 모든 미국 주와 함께 선택 드롭 다운 목록을 생성하여 수동으로 입력 할 필요가 없는지 궁금합니다. 온라인으로 검색했지만 찾을 수 없습니다. 모든 상태를 수동으로 입력 할 필요가 없도록 수행 할 작업에 대한 제안 사항이 있습니까?


일부 도우미 파일

def us_states
    [
      ['Alabama', 'AL'],
      ['Alaska', 'AK'],
      ['Arizona', 'AZ'],
      ['Arkansas', 'AR'],
      ['California', 'CA'],
      ['Colorado', 'CO'],
      ['Connecticut', 'CT'],
      ['Delaware', 'DE'],
      ['District of Columbia', 'DC'],
      ['Florida', 'FL'],
      ['Georgia', 'GA'],
      ['Hawaii', 'HI'],
      ['Idaho', 'ID'],
      ['Illinois', 'IL'],
      ['Indiana', 'IN'],
      ['Iowa', 'IA'],
      ['Kansas', 'KS'],
      ['Kentucky', 'KY'],
      ['Louisiana', 'LA'],
      ['Maine', 'ME'],
      ['Maryland', 'MD'],
      ['Massachusetts', 'MA'],
      ['Michigan', 'MI'],
      ['Minnesota', 'MN'],
      ['Mississippi', 'MS'],
      ['Missouri', 'MO'],
      ['Montana', 'MT'],
      ['Nebraska', 'NE'],
      ['Nevada', 'NV'],
      ['New Hampshire', 'NH'],
      ['New Jersey', 'NJ'],
      ['New Mexico', 'NM'],
      ['New York', 'NY'],
      ['North Carolina', 'NC'],
      ['North Dakota', 'ND'],
      ['Ohio', 'OH'],
      ['Oklahoma', 'OK'],
      ['Oregon', 'OR'],
      ['Pennsylvania', 'PA'],
      ['Puerto Rico', 'PR'],
      ['Rhode Island', 'RI'],
      ['South Carolina', 'SC'],
      ['South Dakota', 'SD'],
      ['Tennessee', 'TN'],
      ['Texas', 'TX'],
      ['Utah', 'UT'],
      ['Vermont', 'VT'],
      ['Virginia', 'VA'],
      ['Washington', 'WA'],
      ['West Virginia', 'WV'],
      ['Wisconsin', 'WI'],
      ['Wyoming', 'WY']
    ]
end

어떤 형태로든

<%= select_tag :state, options_for_select(us_states) %>

감사합니다 Codeglot. 누군가가 전체 이름 대신 2 자로 된 상태 약어를 표시하려는 경우 :

def us_states
  [
    ['AK', 'AK'],
    ['AL', 'AL'],
    ['AR', 'AR'],
    ['AZ', 'AZ'],
    ['CA', 'CA'],
    ['CO', 'CO'],
    ['CT', 'CT'],
    ['DC', 'DC'],
    ['DE', 'DE'],
    ['FL', 'FL'],
    ['GA', 'GA'],
    ['HI', 'HI'],
    ['IA', 'IA'],
    ['ID', 'ID'],
    ['IL', 'IL'],
    ['IN', 'IN'],
    ['KS', 'KS'],
    ['KY', 'KY'],
    ['LA', 'LA'],
    ['MA', 'MA'],
    ['MD', 'MD'],
    ['ME', 'ME'],
    ['MI', 'MI'],
    ['MN', 'MN'],
    ['MO', 'MO'],
    ['MS', 'MS'],
    ['MT', 'MT'],
    ['NC', 'NC'],
    ['ND', 'ND'],
    ['NE', 'NE'],
    ['NH', 'NH'],
    ['NJ', 'NJ'],
    ['NM', 'NM'],
    ['NV', 'NV'],
    ['NY', 'NY'],
    ['OH', 'OH'],
    ['OK', 'OK'],
    ['OR', 'OR'],
    ['PA', 'PA'],
    ['RI', 'RI'],
    ['SC', 'SC'],
    ['SD', 'SD'],
    ['TN', 'TN'],
    ['TX', 'TX'],
    ['UT', 'UT'],
    ['VA', 'VA'],
    ['VT', 'VT'],
    ['WA', 'WA'],
    ['WI', 'WI'],
    ['WV', 'WV'],
    ['WY', 'WY']
  ]
end

이를 위해 일반적으로 Carmen 및 Carmen-Rails 보석을 사용합니다.

https://github.com/jim/carmen

https://github.com/jim/carmen-rails

내 프로젝트는 여전히 모두 Ruby 1.8에 있으므로 특정 ruby-18 브랜치를 사용해야하므로 Gemfile에 다음이 있습니다.

gem 'carmen', :git => 'git://github.com/jim/carmen.git', :tag => 'ruby-18'
gem 'carmen-rails', :git => 'git://github.com/jim/carmen-rails.git'

그런 다음 : address 모델 객체의 : state_code 필드를 편집하는 양식에서 모든 미국 주에 대한 선택 태그를 생성하려면 ...

subregion_select(:address, :state_code, Carmen::Country.coded('US'))

이것은 더 자세한 연습입니다. Rails 4를 사용하고 있습니다.

helpers 폴더 아래에 states_helper.rb를 만들었습니다.

states_helper.rb 내부 :

module StatesHelper

def us_states
  [
    ['Alabama', 'AL'],
    ['Alaska', 'AK'],
    ['Arizona', 'AZ'],
    ['Arkansas', 'AR'],
    ['California', 'CA'],
    ['Colorado', 'CO'],
    ['Connecticut', 'CT'],
    ['Delaware', 'DE'],
    ['District of Columbia', 'DC'],
    ['Florida', 'FL'],
    ['Georgia', 'GA'],
    ['Hawaii', 'HI'],
    ['Idaho', 'ID'],
    ['Illinois', 'IL'],
    ['Indiana', 'IN'],
    ['Iowa', 'IA'],
    ['Kansas', 'KS'],
    ['Kentucky', 'KY'],
    ['Louisiana', 'LA'],
    ['Maine', 'ME'],
    ['Maryland', 'MD'],
    ['Massachusetts', 'MA'],
    ['Michigan', 'MI'],
    ['Minnesota', 'MN'],
    ['Mississippi', 'MS'],
    ['Missouri', 'MO'],
    ['Montana', 'MT'],
    ['Nebraska', 'NE'],
    ['Nevada', 'NV'],
    ['New Hampshire', 'NH'],
    ['New Jersey', 'NJ'],
    ['New Mexico', 'NM'],
    ['New York', 'NY'],
    ['North Carolina', 'NC'],
    ['North Dakota', 'ND'],
    ['Ohio', 'OH'],
    ['Oklahoma', 'OK'],
    ['Oregon', 'OR'],
    ['Pennsylvania', 'PA'],
    ['Puerto Rico', 'PR'],
    ['Rhode Island', 'RI'],
    ['South Carolina', 'SC'],
    ['South Dakota', 'SD'],
    ['Tennessee', 'TN'],
    ['Texas', 'TX'],
    ['Utah', 'UT'],
    ['Vermont', 'VT'],
    ['Virginia', 'VA'],
    ['Washington', 'WA'],
    ['West Virginia', 'WV'],
    ['Wisconsin', 'WI'],
    ['Wyoming', 'WY']
  ]
end
end

구성-> 환경에서 다음을 development.rb 및 production.rb 안에 넣었습니다.

config.action_controller.include_all_helpers = true

마지막으로, 내 뷰 안에 넣습니다 (Slim HTML로 입력).

= form_for :order_submissions, url: order_url, html: { id: "order_form"} do |f|
fieldset
.form-group
  = f.select(:state, options_for_select(us_states, "CA"))

"CA"는로드시 드롭 다운 메뉴에서 캘리포니아를 미리 선택합니다.

참고 : select_tag. 그것을 사용하면 정의되지 않은 메서드 오류가 발생했습니다 select_tag(select_tag는 Ruby 가이드에 있습니다. 어떻게 정의되지 않을 수 있습니까?) select.


이 작업을하도록하기 위해 이렇게했습니다 simple_form.

user.rb모델에 추가 :

STATES = 
  [
    ['Alabama', 'AL'],
    ['Alaska', 'AK'],
    ['Arizona', 'AZ'],
    ['Arkansas', 'AR'],
    ['California', 'CA'],
    ['Colorado', 'CO'],
    ['Connecticut', 'CT'],
    ['Delaware', 'DE'],
    ['District of Columbia', 'DC'],
    ['Florida', 'FL'],
    ['Georgia', 'GA'],
    ['Hawaii', 'HI'],
    ['Idaho', 'ID'],
    ['Illinois', 'IL'],
    ['Indiana', 'IN'],
    ['Iowa', 'IA'],
    ['Kansas', 'KS'],
    ['Kentucky', 'KY'],
    ['Louisiana', 'LA'],
    ['Maine', 'ME'],
    ['Maryland', 'MD'],
    ['Massachusetts', 'MA'],
    ['Michigan', 'MI'],
    ['Minnesota', 'MN'],
    ['Mississippi', 'MS'],
    ['Missouri', 'MO'],
    ['Montana', 'MT'],
    ['Nebraska', 'NE'],
    ['Nevada', 'NV'],
    ['New Hampshire', 'NH'],
    ['New Jersey', 'NJ'],
    ['New Mexico', 'NM'],
    ['New York', 'NY'],
    ['North Carolina', 'NC'],
    ['North Dakota', 'ND'],
    ['Ohio', 'OH'],
    ['Oklahoma', 'OK'],
    ['Oregon', 'OR'],
    ['Pennsylvania', 'PA'],
    ['Puerto Rico', 'PR'],
    ['Rhode Island', 'RI'],
    ['South Carolina', 'SC'],
    ['South Dakota', 'SD'],
    ['Tennessee', 'TN'],
    ['Texas', 'TX'],
    ['Utah', 'UT'],
    ['Vermont', 'VT'],
    ['Virginia', 'VA'],
    ['Washington', 'WA'],
    ['West Virginia', 'WV'],
    ['Wisconsin', 'WI'],
    ['Wyoming', 'WY']
  ]

내 관점에서 simple_form을 다음과 같이 사용했습니다.

<%= simple_form_for(@user) do |f| %>    
    <%= f.input :state, as: :select, collection: User::STATES %>
    <%= f.button :submit %>
<% end %>

헬퍼를 사용하여 상태를 포함하는 데 문제가 있음을 발견했습니다. 새 레코드를 만들 때 완벽하게 작동하지만 기존 레코드를 편집하려면 드롭 다운 상자에서 데이터베이스의 상태를 미리 선택하고 싶습니다. 도우미를 사용하여 작동하지 못했습니다. 그러나 간단한 상태 테이블을 생성하면 작동합니다. 나를 위해 일한 것은 다음과 같습니다.

선택 상자 옵션에 대한 상태 테이블 만들기

state_code 및 state_name (또는 원하는 이름)에 대한 열만있는 상태 모델 파일 및 데이터베이스 테이블을 생성합니다. rails g model State state_code:string:uniq state_name:string --no-timestamps --no-test-framework. 그러면 db / migrate 폴더에 마이그레이션 파일이 생성됩니다. id 열을 원하지 않는 경우 , id: falsecreate_table 블록 선언 에 삽입 하여 편집 할 수 있습니다 .

# db/migrate/timestamp_create_states.rb
class CreateStates < ActiveRecord::Migration
  def change
    create_table :states, id: false do |t|
      t.string :state_code, null: false
      t.string :state_name
    end
    add_index :states, :state_code, unique: true
  end
end

그리고 데이터베이스를 마이그레이션하십시오 rake db:migrate.

You can populate the table using the seed file. Make sure to delete or comment out any previously loaded data in the seed file so you don't add duplicates.

#db/seeds.rb
states = State.create!([
  { state_name: 'Alaska', state_code: 'AK' },
  { state_name: 'Alabama', state_code: 'AL' },
  { state_name: 'Arkansas', state_code: 'AR' },
  { state_name: 'Arizona', state_code: 'AZ' },
  { state_name: 'California', state_code: 'CA' },
  { state_name: 'Colorado', state_code: 'CO' },
  { state_name: 'Connecticut', state_code: 'CT' },
  { state_name: 'District of Columbia', state_code: 'DC' },
  { state_name: 'Delaware', state_code: 'DE' },
  { state_name: 'Florida', state_code: 'FL' },
  { state_name: 'Georgia', state_code: 'GA' },
  { state_name: 'Hawaii', state_code: 'HI' },
  { state_name: 'Iowa', state_code: 'IA' },
  { state_name: 'Idaho', state_code: 'ID' },
  { state_name: 'Illinois', state_code: 'IL' },
  { state_name: 'Indiana', state_code: 'IN' },
  { state_name: 'Kansas', state_code: 'KS' },
  { state_name: 'Kentucky', state_code: 'KY' },
  { state_name: 'Louisiana', state_code: 'LA' },
  { state_name: 'Massachusetts', state_code: 'MA' },
  { state_name: 'Maryland', state_code: 'MD' },
  { state_name: 'Maine', state_code: 'ME' },
  { state_name: 'Michigan', state_code: 'MI' },
  { state_name: 'Minnesota', state_code: 'MN' },
  { state_name: 'Missouri', state_code: 'MO' },
  { state_name: 'Mississippi', state_code: 'MS' },
  { state_name: 'Montana', state_code: 'MT' },
  { state_name: 'North Carolina', state_code: 'NC' },
  { state_name: 'North Dakota', state_code: 'ND' },
  { state_name: 'Nebraska', state_code: 'NE' },
  { state_name: 'New Hampshire', state_code: 'NH' },
  { state_name: 'New Jersey', state_code: 'NJ' },
  { state_name: 'New Mexico', state_code: 'NM' },
  { state_name: 'Nevada', state_code: 'NV' },
  { state_name: 'New York', state_code: 'NY' },
  { state_name: 'Ohio', state_code: 'OH' },
  { state_name: 'Oklahoma', state_code: 'OK' },
  { state_name: 'Oregon', state_code: 'OR' },
  { state_name: 'Pennsylvania', state_code: 'PA' },
  { state_name: 'Puerto Rico', state_code: 'PR' },
  { state_name: 'Rhode Island', state_code: 'RI' },
  { state_name: 'South Carolina', state_code: 'SC' },
  { state_name: 'South Dakota', state_code: 'SD' },
  { state_name: 'Tennessee', state_code: 'TN' },
  { state_name: 'Texas', state_code: 'TX' },
  { state_name: 'Utah', state_code: 'UT' },
  { state_name: 'Virginia', state_code: 'VA' },
  { state_name: 'Vermont', state_code: 'VT' },
  { state_name: 'Washington', state_code: 'WA' },
  { state_name: 'Wisconsin', state_code: 'WI' },
  { state_name: 'West Virginia', state_code: 'WV' },
  { state_name: 'Wyoming', state_code: 'WY' }
])

Then run the rake task to seed the db rake db:seed

In your form you can add this as your select box (I'm using state_code as the field name but you can make it just state or whatever you want):

<%= f.label :state_code, 'State', class: 'control-label' %>
<%= f.collection_select(:state_code, State.select(:state_name, :state_code),
   :state_code, :state_name, {selected: 'CA'}, {class: 'form-control'}) %>

The collection_select helper method format in a Rails form block is f.collection_select(method, collection, value_method, text_method, options = {}, html_options = {}). If you want state_code as both the text and value of the dropdown box then change the :state_name to :state_code in the first select argument and in the text_method (note the text and value orders are reversed). In the options I preselected 'CA', but only do that for a new form not edit (or it will override the value with CA each time). You can change that to a blank {include_blank: true} or add a prompt {prompt: 'Select State'} or just have it default to the selected or first value with an empty hash {}. If you want to make the field required you can add that to the html options {class: 'form-control', required: true}

Now in your form you can populate it from the states table and it will preselect the value when editing a record.


In case this one doesn't work:

<%= select_tag :state, us_states%>

Try this :

 <%=select_tag 'State', options_for_select(us_states),:name=>"state",:id=>"state"%>

You have a gem that can help you: the countries gem which integrates with country_select, so you have a complete solution for states input.

Also if you want to reduce the gem dependency list you can just do:

 <%= f.select :country_code, ::ISO3166::Country.all_names_with_codes,{ include_blank: true } %>

Check this https://rubygems.org/gems/country_state_select

Country State Select is a library that provides an easy API to generate Country , State / Province and City dropdowns for use in forms.

When implemented correctly, a State / Province dropdown is filled with appropriate regions based upon what Country a user has selected .

For instance, if a user chooses "United States of America" for a Country dropdown, the State dropdown will be filled with the 50 appropriate states plus the District of Columbia also then user can list city according to state selection but currently cities are limited.


I don't know if there is something built-in Rails to make a HTML select field filled with U.S.A. states.

But here you have a screencast which explains this: http://railscasts.com/episodes/88-dynamic-select-menus

I hope it will be useful.


I have created a sample project with detailed instructions on how to create drop-downs in Rails 4.2.2 and Ruby 2.2.2 https://rubyplus.com/articles/2501

참고URL : https://stackoverflow.com/questions/6400010/rails-select-drop-down-for-states

반응형