Search code examples
ruby-on-railsjsonhamljbuilder

Using rendered JSON in rails view conditional statement


I have a jbuilder view that returns json which is dynamically rendered in a partial. One of the json attributes is called in_list, which is a boolean value. I'd like to conditionally render a button depending on the value of that boolean. It looks like the boolean gets rendered as a string, but even when taking that into account, the conditional never works. If I render the in_list attribute as the text on the button tag, I can see that it does display True or False correctly, but when used in the conditional, it doesn't work.

code:

.text-center.product_picker_controlls
    - if '{raw-in_list}' == 'true'
        = button_tag 'ADDED', type: 'submit', class: 'btn btn-danger btn-lg t03e', id: 'product-{raw-product_id}'
        -# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
            ADDED
    - else
        = button_tag 'ADD', type: 'submit', class: 'btn btn-primary btn-lg t03e', id: 'product-{raw-product_id}'
        -# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
            ADD

Solution

  • In more closely examining the code, I found that there was a javascript file that replaced all instances of {raw-attribute} with the proper values, so this DOM manipulation was not reaching the ERB itself. My solution was to add the button text and button class directly to the JSON itself, and then add those attributes in the HAML.

    new json in the jbuilder file:

    json.in_list @list.list_items.where(product_id: product[:product_retailer].try(:product_id)).exists? ? 'ADDED' : 'ADD'
    json.button_class @list.list_items.where(product_id: product[:product_retailer].try(:product_id)).exists? ? 'btn-danger' : 'btn-primary'
    

    new haml:

    .text-center.product_picker_controlls
        = button_tag '{raw-in_list}', type: 'submit', class: 'btn btn-lg t03e {raw-button_class}', id: 'product-{raw-product_id}'
        -# %a.btn.btn-primary.btn-lg.t03e{ href: "#{products_path( list_id: args[:list].try(:id) || '0', success: 'back' )}&u={raw-id}", data: { method: :post } }
            '{raw-in_list}'