2016-01-08 14 views
1

我正在使用ruby on rails。尝试设置一个下拉菜单让用户选择他们来自哪个状态。是否可以显示各国作为选项,但记录他们的选择作为state_id?无法获取options_for_select来显示选项

的.erb文件

<% provide(:title, 'New Profile') %> 

    <%= bootstrap_form_for(@profile) do |f| %> 

    <%= f.text_field :name, :autofocus => true, :placeholder => 'Name' %> 
    <%= f.number_field :age, :placeholder => 'Age' %> 
     <%= f.form_group :sex, label: { text: "Sex" } do %> 
     <br> 
     <%= f.radio_button :sex, 'Male', label: "Male", inline: true %> 
     <%= f.radio_button :sex, 'Female', label: "Female", inline: true %> 
    <% end %> 

<%= f.text_field :city, :id => 'gmaps-input-address', :placeholder => "City" %> 

<%= f.select :state_id, options_for_select(State.pluck(:home_state)), :label => "State", :class => "dropdown-menu" %> 

<%= f.submit "Submit", :class =>'btn btn-primary' %> 
<% end %> 

数据库模式,为国家的表

create_table "states", force: :cascade do |t| 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.string "home_state" 
    t.string "code" 
end 

而对于曲线表

create_table "profiles", force: :cascade do |t| 
    t.string "name" 
    t.integer "age" 
    t.string "sex" 
    t.string "city" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "user_id" 
    t.string "home_state" 
    t.float "longitude" 
    t.float "latitude" 
    t.string "aasm_state" 
    t.integer "state_id" 
    end 

回答

1

这绝对有可能的架构。你是接近,但你需要格式化您的形式帮助像这样得到期望的结果:

<%= f.select(:state_id, options_for_select(State.all.collect {|p| [ p.home_state, p.id ]), :label => "State", :class => "dropdown-menu")%> 

更多文档浏览:http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

+0

大加赞赏。 – duwerq

+0

@twolips请记住:一个常见的约定是在模型上用'self.all.collect {| p | [p.home_state,p.id]}'里面。 :)不要重复自己。 –