dimanche 13 septembre 2015

Send 'nil' for unchecked checkboxes - UJS, Rails 4

I am trying to update_attributes for orders using check_box form tags inside an HTML table:

...
<td>
  <%= form_for order, url: toggle_shipped_state_path(order.id), remote: true do |f| %>
    <% if order.shipped_or_delivered.nil? %> #<= items that weren't shipped
      <%= f.check_box :shipped_or_delivered, class: 'toggle-shipped' %>
    <% else %>
      <%= f.check_box :shipped_or_delivered, class: 'toggle-shipped', checked: true %>
    <% end %>
    <%= f.submit 'Shipped' %>
  <% end  %>
</td>
...  

At the end of my view, I'm loading my-sales.js, which has:

jQuery.fn.submitOnCheck = function() {

  this.find('input[type=submit]').remove();
  this.find('input[type=checkbox]').click(function() {
    $(this).parent('form').submit();
    $(this).closest('tr').toggleClass('success');
  });
  return this;
}

$('table').find('input[checked]').each(function(){
    if ($(this).is(':checked')) {
      $(this).closest('tr').addClass('success');
    }
  });

$('form.edit_order').submitOnCheck();

My toggle_shipped_state action is:

def toggle_shipped_state
  @order = Order.find(params[:order_id])
  @order.update_attributes(shipped_or_delivered: Time.now)
end

Checking the box works fine and @order's shipped_and_delivered attribute gets updated correctly. However, unchecking the check box does nothing. How can I make sure that unchecking the checkbox creates an AJAX call to update the corresponding order's shipped_and_delivered attribute with nil ?




Aucun commentaire:

Enregistrer un commentaire