2016-01-08 53 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]}'裏面。 :)不要重複自己。 –