Ruby on Rails Web表单的国家/地区选择

时间:2012-07-09 09:24:58

标签: ruby-on-rails-3

我想在我的Rails网络表单中包含国家/地区选择选择框。如何在Ruby on Rails中实现?我的表格是这样的

<%= form_for :User, :url => {:action => :create } do |f| %>              
  <div class="field">
    <%= f.label :select_countries %><br />
    <%= f.select(:countries, country_list)  %>
  </div>
  <%= f.submit "Create" %>
<% end %>

我可以包含哪些内容来代替country_list?

3 个答案:

答案 0 :(得分:4)

我的意见是在数据库中播种国家/地区列表。

使用字段“name”创建模型国家/地区。

在app / models / country.rb

attr_accessible :name

从YAML文件加载国家/地区列表并将种子加载到数据库中。

在config / country.yml

-
 name: India
 name: Pakistan
 name: Cuba
 #add required country name

在db / seed.rb

COUNTRIES  = YAML.load_file(Rails.root.join('config/country.yml'))
COUNTRIES.each do |country|
  Country.create(country)
end

运行

rake db:seed

在您的用户模型中添加country_id字段(编写迁移到添加字段)。

在app / models / user.rb

class User < ActiveRecord::Base
 #associate user with country
 belongs_to :country
end

在新用户表单中添加以下代码。

 <%= f.select :country_id, Country.all.collect { |country| [country.name, country.id] },
  { :prompt => "Select Country" } %>

答案 1 :(得分:2)

<%= f.country_select :country, ["United States"] %>

它真的适用于country_select gem

答案 2 :(得分:1)

过去,Rails用于提供国家/地区选择功能。该功能已从核心中提取出来,现在已打包到country_select插件中。

使用该插件启用该功能。

相关问题