Array of objects into a collections list for a dropdown

I’ve got objects from an active record query I performed. What’s the best method of getting the names out of that array to generate a dropdown list collection.

Thanks, Joe

Say you’ve got an AR query for Toy.all, and you want to populate a list of toys that a child can play with, and then have a submit button to save things. Here’s a form for a child in a view and the drop-down list so they can choose a toy:

<%= form_for @child do |f| %>
  <%= f.collection_select :toy_id, Toy.all, :id, :name %>
  <%= f.submit %>
<% end %>

You can substitute Toy.all for whatever instance variable you might have set up for this from the controller – @toys or something. (These next two examples of building a drop-down will assume that you’ve done this, but you could still use just Toy.all instead of an instance variable. Considered bad form really, but let your conscience be your guide!)

Another way to get the exact same results in a <select> is this in place of the collection_select:

<%= f.select :user_id, @toys.map { |t| [t.name, t.id] } %>

Or this, which gives a bit more control over how the options get built out, letting you choose a default selected value – in this case as long as one of the toys is named “Cube Puzzle” anyway!

<% default_toy = Toy.find_by(name: 'Cube Puzzle') %>
<%= f.select :user_id, options_for_select(@toys.map { |t| [t.name, t.id] },
                                          default_toy.id) %>

Thanks, mapping the id and name from the object helped!