display list of days in a week in Rails using Date::DAYNAMES
Asked Answered
E

3

12

I'm having trouble displaying a list of days in a week in a form.

<%= form_for [@hourable, @hour] do |f| %>

  <% days = []
  Date::DAYNAMES.each_with_index { |x, i| days << [x, i] } %>

  <% days.each_with_index do |day,index| %>

  <div class="field">
    <%= f.check_box day[0] %>
  </div>

  <% end %>   

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I'm getting error

undefined method `Sunday' for #<Hour:0x007fe13c764010>

But if I just display

<%= day[0] %>, it will give me a list Sunday, Monday, Tuesday, etc... to Saturday

What am I doing wrong here?

Thanks

Exaggeration answered 26/6, 2013 at 3:21 Comment(0)
F
24

Replace

<% days = []
 Date::DAYNAMES.each_with_index { |x, i| days << [x, i] } %>

<% days.each_with_index do |day,index| %>

<div class="field">
 <%= f.check_box day[0] %>
</div>

With

 <%= f.label :FIELD_NAME%>
<% Date::DAYNAMES.each do |day| %>
  <%= f.check_box :FIELD_NAME, {}, day %>
  <%= day %>
<% end %>
Fructificative answered 26/6, 2013 at 3:28 Comment(2)
Thanks for your answer, but I'm trying to figure out how to add a f.label to this. When I try to do f.label :day do, with f.check_box :day, all the input name is the same. How do I change the name so label will match with input? If I'm keeping the same :FIELD_NAME or in my case is :day, it is going to be all the same throughout the loop.Exaggeration
label should come once while day comes seven times, I've edited the answer btwFructificative
D
2

The issue here is calling each_with_index on days, since days is an array of arrays the way you've constructed it, where each element has the form [dayname, index].

Instead of building up days, you can work off of the DAYNAMES array directly, or replace days.each_with_index with just days.each do |x, i| (but personally I think this is extraneous).

Also see http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-select_day and Rails non-table drop down list if you're not tied to checkboxes.

Damaris answered 26/6, 2013 at 3:28 Comment(0)
S
0

I had to require 'date' in ruby 3.2.0 before trying to access its constants.

Snuffy answered 27/12, 2022 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.