Rails non-table drop down list
Asked Answered
L

3

13

I need to have a drop down list in which the user selects the day of the week they want to come in every week. The values will never change right. It's just Sunday, Monday, ..., Saturday right? It seems like more work than needed to make a table and put the days of the week in. I certainly don't need the ability to create, update or delete them. Is there a simple way to handle something like this? Or maybe instead of days of the week it could be status like off, park, reverse, neutral, drive. The main thing is that the values are never going to change. There are just a few of them. So why make a table? I am thinking that there is a way to create a model that already has data in it but I could be wrong.

Longicorn answered 12/3, 2009 at 8:56 Comment(0)
K
28

Why create a model? Just use select.

DAYS = ['Monday', 'Tuesday', 'Wednesday', ...]
select(:event, :day, DAYS)

It's usually better practice to place the constant in the relevant model and use it from there.

In your model:

class Event < ActiveRecord::Base
  DAYS = ['Monday', 'Tuesday', 'Wednesday', ...]
end

and then in your view:

select(:event, :day, Event::DAYS)

and here's another trick I use a lot:

select(:event, :day, Event::DAYS.collect {|d| [d, Event::DAYS.index(d)]})
Kmeson answered 12/3, 2009 at 9:13 Comment(3)
I don't want to be rude or something, but as a newbie rails developer as I am, I cannot understand how to apply your suggestion? What will my view contain and how would I access what you suggest?Pit
the select() goes in your view, wherever you want the dropdown list to appear. the DAYS constant goes in your relevant model.Outdoor
if there's no relevant model (you're not storing this anywhere), then DAYS could go in your view too (or better yet, in an initializer).Outdoor
M
9

Note that Ruby has the English names for the days of the week already built into its date class. You should try to leverage that if you can. Here's the rdoc.

Then as Can has suggested just do the following:

select(:event, :day, Date::DAYNAMES)

Keep in mind that this solution is NOT particularly i18n friendly. If i18n is an issue, I would also check out the localized dates plugin and the changes that were made in Rails 2.2 to support i18n.

Moreta answered 14/3, 2009 at 18:59 Comment(0)
W
6

Try this:

<%= select_tag(:week_day, options_for_select([['Sunday', 'Sun'], ['Monday', 'Mon'], ...])) %> 

See http://guides.rubyonrails.org/form_helpers.html#theselectandoptionstag

Whiney answered 12/3, 2009 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.