gustavgans
gustavgans

Reputation: 5191

rails helper for select_tag?

I don't get the point how can I do that code with an select helper?

<select name="cube_name">
    <% @cube_names.each do |cube| %>
     <option value="<%= cube %>" <% if @cube_name == cube %> selected="selected"<% end %>><%= cube %></option>
    <% end %>
</select>

I have a list (@cube_names) and want a HTML select box width all values of the list and the default value (param @cube_name) should be selected.

thanks.

Upvotes: 0

Views: 874

Answers (1)

Sinan Taifour
Sinan Taifour

Reputation: 10825

The select_tag helper will not auto-set the selected attribute on an item you pass. It just builds the tag. Use something like:

<%= select_tag("id_of_my_tag", @cube_names.map { |cn| "<option#{cn == cube ? " selected='selected'" : ""}>#{cn}</option>" }.join("")) %>

The first parameter is the id of the select tag, the second is a list of options (here built by mapping the cube names to strings, then joining the array into a single string).

You could alternatively use the options_for_select to build the string:

<%= select_tag("id_of_my_tag", options_for_select(@cube_names, cube)) %>

Upvotes: 4

Related Questions