duwerq
duwerq

Reputation: 99

Can't get options_for_select to display choices

I'm working in ruby on rails. Trying to get set-up a drop-down menu for users to choose what state they're from. Is it possible to show the States as an option but record their selection as the state_id?

The .erb file

<% 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 %>

The database schema for the state's table

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

And the schema for the profiles table

  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

Upvotes: 1

Views: 206

Answers (1)

NM Pennypacker
NM Pennypacker

Reputation: 6942

That is definitely possible. You were close, but you need to format your form helper like this to get the desired result:

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

More docs here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Upvotes: 2

Related Questions