3

I am using Rails (3.2.5 with ruby 1.9.3) and mongodb with mongoid. I'd like to give the user the option to check weekdays. Therefore I have a field with type hash in my controller:

field :wochentage, :type => Hash, default: {  :mo => 0,
                                            :di => 0,
                                            :mi => 0,
                                            :dn => 0,
                                            :fr => 0,
                                            :sa => 0,
                                            :so => 0
                                          }

The problem is that I cannot get this to work in the web form:

<% for d,v in @timetable.wochentage  %>
    <td><%= f.check_box :wochentage[d]%></td>
<% end %>

The error I get is:

can't convert Symbol into Integer

Can anyone please point me to the right direction? Thanks in advance, Sven

OK, a little step further: with the fields_for form helper I got closer:

<%= f.fields_for :wochentage do |w| %>
      <td><%= w.check_box :mo %></td>
      <td><%= w.check_box :di %></td>
      <td><%= w.check_box(:mi, checked_value: "1", unchecked_value: "0") %></td>
      <td><%= w.check_box :dn %></td>
      <td><%= w.check_box :fr %></td>
      <td><%= w.check_box :sa %></td>
      <td><%= w.check_box :so %></td>
    <% end %>

With this code I can set the weekday. But it won't read it from the DB, if I want to edit it though it is stored correctly: Wochentage: {"mo"=>"0", "di"=>"0", "mi"=>"1", "dn"=>"0", "fr"=>"0", "sa"=>"0", "so"=>"0"}

In the edit form all checkboxes are unchecked. So how can I make the checkbox show up in the correct status?

Thanks, S

2
  • Even if you answer your own question you still should accept it. It will mark question as answered an you will be awarded with nice bronze badge :) Commented Sep 24, 2012 at 7:15
  • Thanks for the hint, I was searching for a way to mark it as answered... Commented Sep 25, 2012 at 5:27

1 Answer 1

9

OK, I got it:

<%= f.fields_for :wochentage do |w| %>
  <% @timetable.wochentage.each do |t,v| %>
    <td><%= w.check_box t, checked: (v == "1" ? "checked" : "") %></td>
  <% end %>
<% end %>

The funny thing: Normal check_box saves checked as true, unchecked as false. When you have multiple checkboxes for a field as hash the checkboxes save 1 for checked, 0 for unchecked.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.