0
votes

I have a rails gift option check_box_tag that defaults to unchecked (false). The ajax call correctly posts the data when checked (true), but I am struggling to figure out how to persist the data across pages. For instance, if I select gift option then go back to shopping, when I enter the cart page again, I should see the checkbox is still selected. I've explored the docs and played around with putting current_cart.gift_option in different places within the tag, but I can't figure out how to get the checkbox to show as checked if it's "true" in the database.

show.html.haml

%div.cart-tfoot-gift-option.gift-option-container
   %h4.hdr.hdr-quinary Is this order a gift?

       %span.form-group-controls
         = check_box_tag :gift_option, current_cart.gift_option ? 'true' : 'false', id: 'gift_option'
            %label#gift_label.tooltip{:for => 'gift_option'}
               Yes, don't display price on packing slip.

Cart.js.coffe

gift_option: ->
    $checkbox = $('#gift_option')
    $message_container = $('#add-gift-message')
    $message_input = $('#gift_message')

    $checkbox.on 'change', (event) ->
      if $(this).prop('checked')
        q.Ajax.message("Adding gift option")
        setTimeout () ->
          q.Ajax.remove()
        , 1000
        method_data = { 'gift_option': $checkbox.prop('checked'), 'gift_message': $message_input.val() }
        q.Cart.giftAjax(method_data, $message_container.show())

      else
        q.Ajax.message("Removing gift option")
        setTimeout () ->
          q.Ajax.remove()
        , 1000
        method_data = { 'gift_option': $checkbox.prop('checked'), 'gift_message': $message_input.val() }
        q.Cart.giftAjax(method_data, $message_container.hide())

    $message_input.keyup _.debounce((->
      method_data = { 'gift_option': $checkbox.prop('checked'), 'gift_message': $message_input.val() }
      q.Cart.giftAjax(method_data)
    ), 1000)
1

1 Answers

1
votes

It looks like the issue is with your check_box_tag helper in the view. You seem to be setting the value option as 'true' or 'false' (depending on the value of gift_option), but not the checked option (defaults to false). Try something like:

= check_box_tag 'gift_option', 'true', current_cart.gift_option, id: 'gift_option'

(The value 'true' will be posted only if box is checked.)

See http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag