Ive been staring at this for a good day now and i dont understand what ive done wrong.
i want this to produce a list of activities with checkboxes, but if one of the activities is in the users_activity table then that that activities check box will be checked. However the code below displays the activity three times and chekcs all the boxes.
<fieldset>
<table>
<tr>
<th>Activity ID</th>
<th>Activity Name</th>
</tr>
<% @Activitys.each do |activity| %>
<% @users_activity.each do |ua| %>
<% if activity.id == ua.activity_id %>
<tr>
<td><%= activity.id %></td>
<td><%= activity.activity_name%></td>
<td><input name="check_<%= activity.id %>" type="checkbox" checked="yes"></td>
</tr>
<% else %>
<tr>
<td><%= activity.id %></td>
<td><%= activity.activity_name%></td>
<td><input name="check_<%= activity.id %>" type="checkbox" checked="no"></td>
</tr>
<% end %>
<% end %>
<% end %>
</table>
</fieldset>
Its probably really easy but you know what happens when you stare at a piece of code for too long…
The reason all the checkboxes are checked is that the presence of the
checkedattribute on an HTML checkbox causes it to be checked regardless of the attribute’s value. i.e.<input type="checkbox" checked="no">results in a checked checkbox. For the checkboxes that should not be checked you need to write the code such that they do not have acheckedattribute at all.The reason that you are seeing more checkboxes than you expect is because you have the
@users_activity.eachloop nested inside your@Activitys.eachloop and in both theifand theelsecase you always output a checkbox so this results in@Activitys.length * @users_activity.lengthcheckboxes.One solution is to collect the activity IDs of all the user activities once outside your loops i.e.
(you could also move this to the controller)
Then have just the
@Activitys.eachloop in which you generate the checkbox with something likeAlso,
@Activitysshould probably be called@activitiesas starting the variable name with a capital letter indicates that it is a constant in Ruby.