Search code examples
ruby-on-rails-4selectmenufinder

In RoR, how do I get the name/id of my object to render in my select menu instead of the object itself?


I’m using Rails 4.2.3. I have the following helper method for getting US states …

  def us_states
    us_country = Country.find_by_iso('US')
    State.where(country_id: us_country.id)
  end

Then in my view I have

<%= addr.select :state, us_states.collect {|s| [ s.name, s.id ] }, {prompt: 'Select State'}, class: "selectField selectMenu form-control" %>

However, what is being rendered in my view is

<select name="my_object[address][state]" id="my_object_address_state"><option value="">Select State</option>
<option value="#<State:0x007f9f562fe368>">#&lt;State:0x007f9f562fe368&gt;</option>
…
<option value="#<State:0x007f9f563124a8>">#&lt;State:0x007f9f563124a8&gt;</option></select>

How do I make the actual names and IDs of the states appear in my select tag?


Solution

  • You are missing options_for_select, Change your select with this:

    <%= addr.select :state, options_for_select(us_states.collect{|s| [ s.name, s.id ]}), {prompt: 'Select State'}, class: "selectField selectMenu form-control" %>