Reputation: 19713
When a user submits without any boxes checked. I need my ODM (Mongoid) to update the record appropriately.
Having a bit of trouble with:
<% Notification.all.each do |notification| %>
<li>
<%= check_box_tag 'user[notification_ids][]', notification.id, @user.notifications.include?(notification) %>
<%= label_tag notification.description %>
</li>
<% end %>
The doc suggests that the check_box helper puts in a hidden input. The hidden field has the same name and its attributes mimic an unchecked check box. However, with the above code. I am going through a loop. Which is slightly different.
I tried:
<%= check_box('user_notification_ids_', '', options = {:index => notification.id, :checked => @user.notifications.include?(notification)}, checked_value = "1", unchecked_value = "0") %>
But whenever I submit, I get: illegal ObjectId format
Or should I create the hidden tag for notification_ids manually? Something like:
<%= hidden_field_tag 'user[notification_ids][]', '[]' %>
Looking to hear your feedback
Upvotes: 2
Views: 865
Reputation: 804
Go with the first loop you included. It looks much simpler and looks like it does the same thing.
If I understand your first sentence correctly, it sounds like you aren't seeing the user's notifications getting updated to none when they uncheck all the check boxes. When there are no check boxes checked, the browser won't send that param back. It simply won't be included in params
so when you do something like:
@user.update_attributes(params[:user])
... notifications won't get updated. In your controller, do this to ensure there is something set for params[:user][:notifications]
:
params[:user][:notifications] ||= []
This is will set it to an empty array if there if it doesn't exists and/or there's no value there. This ensures that update_attributes
will set it to none/empty.
Upvotes: 1
Reputation: 36944
check_box_tag
doesn't generate any hidden field. check_box
does, but looking at your situation, I think using check_box_tag
is more appropriate since the check_box
method is mainly used for boolean field. Here is one way to do it.
<%= hidden_field_tag 'user[notification_ids][]' %>
<% Notification.all.each do |notification| %>
<li>
<%= check_box_tag 'user[notification_ids][]', notification.id, @user.notifications.include?(notification) %>
<%= label_tag notification.description %>
</li>
<% end %>
When the form is submitted with the checkboxes for Notification of id 2 and 3 checked, the value for params[:user]
is { "notification_ids" => ["", "2", "3"] }
. When nothing is checked, params[:user]
is {"notification_ids"=>[""]}
, which will clear the user's notifications. This works because empty string is ignored by ActiveRecord. From here, we can use the usual @user.update_attributes(params[:user])
to update the User model.
Upvotes: 1