Reputation: 373
I have a select with all months of the year as numbers (1,2,3...12) and a method which converts the number of the month to its name. Ex: (1->January, 2->February...)
I'd like to use it on a select
, showing the name of the month instead of the number.
My question is, how do I generate a select passing this method to my options_for_select
below?
<div class="ls-custom-select">
<%=
form.select(
:month,
options_for_select((1..12), selected: @current_month),
{},
{ class: "ls-select" }
)
%>
</div>
Thanks in advance
Upvotes: 0
Views: 301
Reputation: 101811
You can get seperate text and values by using an array of pairs:
options_for_select([["January", 1], ["February", 2]])
# => <option value="1">January</option>
# => <option value="2">February</option>
You can get localized month names by using the Rails 18n module:
(1..12).to_a.zip(I18n.t("date.month_names").drop(1))
# => [[1, "January"], [2, "February"], [3, "March"], [4, "April"], [5, "May"], [6, "June"], [7, "July"], [8, "August"], [9, "September"], [10, "October"], [11, "November"], [12, "December"]]
.zip
merges two arrays together into pairs. .drop(1)
is needed since the first element in the month_names array is nil (there is no month 0).
<div class="ls-custom-select">
<%=
form.select(
:month,
options_for_select(
(1..12).to_a.zip(I18n.t("date.month_names").drop(1),
@current_month # selected
)
{},
{ class: "ls-select" }
)
%>
</div>
You don't need to write a method to get month names. Use I18n.t("date.month_names")[number]
. Or if localization is not important use Date::MONTHNAMES[number]
.
Upvotes: 1