views:

21

answers:

2

Hi,

I have an index.rhtml with this code

<select id="subtable" name="subtable" size="20" style="width: 400px">
      <% for haus in @hauses %> 
           <option selected value="<%= haus.id %>"><%= haus.timebuild%></option>
       <% end %>
</select>

It will show me a list of drop down files in a select box. However, everytime I refresh the page, the default selected value is always the last of the list (the bottom one). How can I make the default selected value to be the 1st one (the top one of the list), and not the last one?

Thank you

A: 

You can use options_from_collection_for_select. Replace the for loop with this:

options_from_collection_for_select(@hauses, 'id', 'timebuild', @hauses.first.id)
Matt
So in index.rhtml , I wrote this <options_from_collection_for_select(@hauses, 'id', 'timebuild', @hauses.first.id)> </option> , however seems that I have to use the for loop. Because when I tried your code, the list of files in the select table just vanish (without no error)
heike
ah, i know what I did wrong. thank you!
heike
+2  A: 

The selected attribute is supposed to be placed on only the default-selected value, but you're putting it on all values, causing the last one to remain selected.

The simplest solution is just remove the selected attribute altogether.

You should probably use Rails view helpers, which handles this for you (and doing things like automatically default to the current attribute's value):

options_from_collection_for_select(@hauses, 'id', 'timebuild', @hauses.first.id)
Mark Thomas
I tried the code, but it eventually ended up creating a blank select table. If I use the for loop, it renders correctly, but the problem is just the default selection. So is it not possible to add other parameter in the <option selected value> that points to the 1st field?
heike
AHA! now I know what's wrong.. it should be with <%= > and not <option> </option>
heike