Rails Select Drop Down for States?

2019-01-21 01:37发布

I was wondering if maybe there was some already built in function for rails so that it would create a select drop down list with all the U.S. states so I wouldn't have to enter it manually. I searched online but I was unable to find any. Any suggestions on what to do so I don't have to manually enter all the states?

11条回答
啃猪蹄的小仙女
2楼-- · 2019-01-21 01:58

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-21 02:01

Thanks Codeglot. In case anyone is wanting to display the 2-letter state abbreviation instead of the full name:

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
查看更多
4楼-- · 2019-01-21 02:02

This is a more detailed walkthrough. I'm using Rails 4:

Under the helpers folder I created states_helper.rb

Inside 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

Under config -> environments I put the following inside development.rb and production.rb

config.action_controller.include_all_helpers = true

Finally, inside my view I put (this is typed out in 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"))

The "CA" pre-selects California in the dropdown menu on load.

NOTE: I did NOT use select_tag. Using it gave me an undefined method error for select_tag (select_tag is in the Ruby guides, how can it be undefined?) Using just select made it work.

查看更多
倾城 Initia
5楼-- · 2019-01-21 02:07

I found a problem with using a helper to contain the states. It works perfectly when creating a new record but if I want to edit an existing record I want the state in the database to be preselected in the dropdown box. I couldn't get that to work using the helper. But it does work if you create a simple states table. Here's what worked for me:

Create a states table for the select box options

Generate a State model file and database table that only has columns for state_code and state_name (or whatever you want to call them). rails g model State state_code:string:uniq state_name:string --no-timestamps --no-test-framework. This will generate a migration file in the db/migrate folder. If you don't want an id column you can edit it by inserting , id: false into the create_table block declaration.

# 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

And migrate the database 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.

查看更多
smile是对你的礼貌
6楼-- · 2019-01-21 02:09

For this I typically use the Carmen and Carmen-Rails gems.

https://github.com/jim/carmen

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

Since my projects are still all on Ruby 1.8, I have to use the specific ruby-18 branch, so I have the following in my Gemfile:

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

Then, to create the select tag for all US states in a form where you're editing the :state_code field of an :address model object...

subregion_select(:address, :state_code, Carmen::Country.coded('US'))
查看更多
【Aperson】
7楼-- · 2019-01-21 02:10

To get this to work with simple_form, I did this.

Added this to my user.rb model:

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']
  ]

Made the simple_form in my view use that:

<%= simple_form_for(@user) do |f| %>    
    <%= f.input :state, as: :select, collection: User::STATES %>
    <%= f.button :submit %>
<% end %>
查看更多
登录 后发表回答