Skip to main content

Switch state of boolean field

General • Asked by Benny Maas

Hi,

on my index page i want to place a button for each record where i can switch the state from active to inactive or from inactive to active.
the button should change without refreshing the page.

How can i achieve that?

Thanks

Benny


You'll have to do most of that in Javascript. When you click the button you'll send an AJAX request to the server (which can just hit the update action) and that will save the active/inactive state. That's really about it. You might checkout the ajax episode to wrap your head around this: https://gorails.com/episodes/jquery-ujs-and-ajax?autoplay=1


Hi Chris,

i got it working.
Is this OK or is there a better way to implement this?

my routes

resources :products do
    member do
        patch :toggle_enable_status
    end
end

products_controller.rb

def toggle_enable_status
    @product.toggle!(:enabled)
end

the link in index.html.erb

<td class="product-<%= product.id %>">
    <%= link_to "#{ product.enabled ? 'Enabled' : 'Disabled' }", toggle_enable_status_product_path(product), method: :patch, remote: :true, class: "btn btn-xs btn-#{ product.enabled ? 'success' : 'warning' }"  %>
</td>

and the toggle_enabled_status.js.erb

console.log(<%= @product.enabled %>);
<% if @product.enabled == true %>
    $(".product-<%= @product.id %> > a").html('Enabled').removeClass('btn-warning').addClass('btn-success')
<% else %>
    $(".product-<%= @product.id %> > a").html('Disabled').removeClass('btn-success').addClass('btn-warning')
<% end %>
$("#product-status-<%= @product.id %>").html("<%= @product.enabled %>")

Benny, this looks great. That's pretty much exactly what I would have suggested. :)

The only thing I'd say is to remove the console.log so that it doesn't crash in certain browsers like IE. For some reason it doesn't support that.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.