Kei9Ahfu
Kei9Ahfu

Reputation: 47

check_box_tag is not accepting values

I have a simple todo app where there is a new page with a form for the model Task and an index page.

When I create a new task at new view: (erledigt means done for the sake of completeness)

 <%= f.check_box(:erledigt,{}, 1, 0) %>

When I fireup rails c

2.0.0-p247 :021 > Task.all.pluck(:erledigt)
(0.2ms)  SELECT `tasks`.`erledigt` FROM `tasks`
=> [1, 1, 0, 0]

I see that the form saves my inputs.

The problem:

In the index view every single tasks is checked why? Can anyone explain or provide any suggestions?

<% @tasks.each do |task| %>
  <tr>
    <td><%= check_box_tag(task.erledigt, 1, 0) %> </td>
    <td><%= link_to task.aufgabe,  task %></td>
    <td><%= task.beschreibung %></td>
    <td><%= task.prioriaet %></td>
    <td><%= link_to 'zeigen', task %></td>
    <td><%= link_to 'LÖSCHEN', task, method: :delete, data: { confirm: 'Sicher?' } %></td>
  </tr>
<% end %>

Basically the index view shows all the tasks with the checkbox and every single task is already checked but it should be checked if the "erledigt" attribute is 1. As you can see there are a few tasks with 0.

Index view right now:

[x] task1

[x] task2

[x] task3

[x] task4

How the index view should be:

[x] task1

[x] task2

[ ] task3

[ ] task4

Upvotes: 0

Views: 160

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53018

All the checkboxes are displayed as checked because you are passing option 0 as checked to the check_box_tag and ruby interprets 0 as a true value.

<td><%= check_box_tag(task.erledigt, 1, 0) %> </td>

Simply, update the above as

<td><%= check_box_tag("task_erledigt",task.erledigt, task.erledigt == 1 ? true: false ) %> </td>

So, based on the value of task.erledigt the checkbox would display checked or unchecked state.

Upvotes: 2

Related Questions