Ruby-on-rails Rails 选择下拉状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6400010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Select Drop Down for States?
提问by Jake
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?
我想知道是否可能已经为 rails 内置了一些函数,以便它会创建一个包含所有美国州的选择下拉列表,这样我就不必手动输入它了。我在网上搜索,但我找不到任何。关于该怎么做的任何建议,这样我就不必手动输入所有状态?
回答by thenengah
some helper file
一些帮助文件
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
in some form
以某种形式
<%= select_tag :state, options_for_select(us_states) %>
回答by Brian
Thanks Codeglot. In case anyone is wanting to display the 2-letter state abbreviation instead of the full name:
感谢 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
回答by fuzzybabybunny
This is a more detailed walkthrough. I'm using Rails 4:
这是一个更详细的演练。我正在使用 Rails 4:
Under the helpers folder I created states_helper.rb
在 helpers 文件夹下我创建了 states_helper.rb
Inside 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
Under config -> environments I put the following inside development.rb and production.rb
在 config -> 环境下,我将以下内容放入 development.rb 和 production.rb
config.action_controller.include_all_helpers = true
Finally, inside my view I put (this is typed out in Slim HTML)
最后,在我的视图中放入(这是在 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.
“CA”在加载时在下拉菜单中预选加利福尼亚。
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 selectmade it work.
注意:我没有使用select_tag. 使用它给了我一个未定义的方法错误select_tag(select_tag 在 Ruby 指南中,它怎么可能是未定义的?)使用刚刚select使它工作。
回答by Tinynumbers
For this I typically use the Carmen and Carmen-Rails gems.
为此,我通常使用 Carmen 和 Carmen-Rails 宝石。
https://github.com/jim/carmen-rails
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:
由于我的项目仍然在 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'
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...
然后,要在编辑 :address 模型对象的 :state_code 字段的表单中为所有美国州创建选择标记...
subregion_select(:address, :state_code, Carmen::Country.coded('US'))
回答by yellowreign
To get this to work with simple_form, I did this.
为了让它与 一起工作simple_form,我这样做了。
Added this to my user.rbmodel:
将此添加到我的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']
]
Made the simple_form in my view use that:
使 simple_form 在我看来使用:
<%= simple_form_for(@user) do |f| %>
<%= f.input :state, as: :select, collection: User::STATES %>
<%= f.button :submit %>
<% end %>
回答by Steve Carey
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: falseinto the create_table block declaration.
生成一个状态模型文件和数据库表,其中只有 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
And migrate the database rake db:migrate.
并迁移数据库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
然后运行 rake 任务来播种数据库 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):
在您的表单中,您可以将其添加为您的选择框(我使用 state_code 作为字段名称,但您可以将其设置为 state 或任何您想要的):
<%= 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}
Rails 表单块中的 collection_select 辅助方法格式是f.collection_select(method, collection, value_method, text_method, options = {}, html_options = {}). 如果您希望 state_code 作为下拉框的文本和值,则在第一个选择参数和 text_method 中将 :state_name 更改为 :state_code(注意文本和值的顺序是相反的)。在选项中,我预先选择了“CA”,但仅对新表单执行此操作而不进行编辑(否则每次都会用 CA 覆盖该值)。您可以将其更改为空白{include_blank: true}或添加提示,{prompt: 'Select State'}或者仅将其默认为所选值或带有空哈希值的第一个值{}。如果您想让该字段成为必需,您可以将其添加到 html 选项中{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.
现在在您的表单中,您可以从状态表中填充它,它会在编辑记录时预选该值。
回答by Sachin Prasad
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"%>
回答by Paulo Fidalgo
You have a gem that can help you: the countries gemwhich integrates with country_select, so you have a complete solution for states input.
您有一个可以帮助您的 gem:与country_select集成的country gem,因此您拥有一个完整的状态输入解决方案。
Also if you want to reduce the gem dependency list you can just do:
另外,如果你想减少 gem 依赖列表,你可以这样做:
<%= f.select :country_code, ::ISO3166::Country.all_names_with_codes,{ include_blank: true } %>
回答by Arvind
Check this https://rubygems.org/gems/country_state_select
检查这个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.
Country State Select 是一个库,它提供了一个简单的 API 来生成用于表单的 Country、State/Province 和 City 下拉列表。
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.
例如,如果用户选择“美国”作为国家下拉列表,则州下拉列表将填充 50 个合适的州和哥伦比亚特区,然后用户可以根据州选择列出城市,但目前城市是有限的。
回答by gsumk
if you want to save state on full name
如果你想在全名上保存状态
# frozen_string_literal: true
module StateHelper
def us_states
[
['Alabama'],
['Alaska'],
['Arizona'],
['Arkansas'],
['California'],
['Colorado'],
['Connecticut'],
['Delaware'],
['District of Columbia'],
['Florida'],
['Georgia'],
['Hawaii'],
['Idaho'],
['Illinois'],
['Indiana'],
['Iowa'],
['Kansas'],
['Kentucky'],
['Louisiana'],
['Maine'],
['Maryland'],
['Massachusetts'],
['Michigan'],
['Minnesota'],
['Mississippi'],
['Missouri'],
['Montana'],
['Nebraska'],
['Nevada'],
['New Hampshire'],
['New Jersey'],
['New Mexico'],
['New York'],
['North Carolina'],
['North Dakota'],
['Ohio'],
['Oklahoma'],
['Oregon'],
['Pennsylvania'],
['Puerto Rico'],
['Rhode Island'],
['South Carolina'],
['South Dakota'],
['Tennessee'],
['Texas'],
['Utah'],
['Vermont'],
['Virginia'],
['Washington'],
['West Virginia'],
['Wisconsin'],
['Wyoming']
]
end
end
And then in form
然后在形式
<%= f.select :state, options_for_select(us_states), class:"form-control", required: true %>

