Forum: Ruby on Rails setting selected option in select

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alex (Guest)
on 2006-06-14 06:17
I am working on employee scheduling app and am trying to set a drop down
list for store hours.  I am having trouble setting a default selected
for the list.  Anybody have any suggestions.  example code is below:

I have an array set in model Storeday

TIME_TYPES =[
[ "12:00am", "0:00" ],
[ "12:15am", "0:15" ],
[ "12:30am", "0:30" ],
[ "12:45am", "0:45" ],
[ "1:00am", "1:00" ],
[ "1:15am", "1:15" ],
[ "1:30am", "1:30" ],
.
.
.
.
[ "11:00pm", "23:00" ],
[ "11:15pm", "23:15" ],
[ "11:30pm", "23:30" ],
[ "11:45pm", "23:45" ]
        ].freeze

In my controller I set
<%time_choices = Storeday::TIME_TYPES%>

Then I have a select helper

      <%=select("storeday", "open_time", time_choices, options =
{:selected => "1:00"})%>

Using this code I can't get the selected to default to the time I want.
Any suggestions??

Thanks

Alex
495ab7ba5de628487069bcc662c3a1aa?d=identicon&s=25 Michel D. (micheldogger)
on 2006-06-14 22:30
Alex,

i might have a solutions. Maybe the code I give can make it work,
after that yo can fine tune it. Here's what I did:

In my model (like you did):
------------------------------------------------
TIME_TYPES =[
["12:00am","01:00" ],
["01:00am","02:00" ],
["02:00am","03:00" ],
["04:00am","05:00" ]].freeze


In my Controller:
------------------------------------------------
def page
  @time_choices = Mymodel::TIME_TYPES
end

I made my time_choices available for my view.
Maybe you don't need to do that!

In my view page.rhtml
------------------------------------------------

<select name="storeday">
<% 4.times do |i| %>
 <option value="<%= @time_choices[i][1]%>"
   <%= ' selected' if @time_choices[i][1] == '02:00' %>>
   <%= @time_choices[i][0]%>
 </option>
<% end %>
</select>

-------------------------------------------------

<% 4.times do |i| %>  =
is the amount of 'rows' in @time_choices

@time_choices[i][1]%> =

01:00
02:00
03:00
05:00

@time_choices[i][0]%> =

12:00am
01:00am
02:00am
04:00am

<%= ' selected' if @time_choices[i][1] == '02:00' %>
selects the option with value 02:00
(= 01:00am in selectmenu)

I'll hope you'll have some usefull information here.
micheldogger
495ab7ba5de628487069bcc662c3a1aa?d=identicon&s=25 Michel D. (micheldogger)
on 2006-06-14 22:34
For you're info,

I've been trying to make :selected work, in you're code:

<%=select("storeday", "open_time", time_choices,
          options = {:selected => "1:00"})%>

I've tried any possible way I no, but I couldn't figure it out.
Maybe someone else?

micheldogger
This topic is locked and can not be replied to.