Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Switch state of boolean field

General • Asked by Benny Maas


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?



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:

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


def toggle_enable_status

the link in index.html.erb

<td class="product-<%= %>">
    <%= 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' }"  %>

and the toggle_enabled_status.js.erb

console.log(<%= @product.enabled %>);
<% if @product.enabled == true %>
    $(".product-<%= %> > a").html('Enabled').removeClass('btn-warning').addClass('btn-success')
<% else %>
    $(".product-<%= %> > a").html('Disabled').removeClass('btn-success').addClass('btn-warning')
<% end %>
$("#product-status-<%= %>").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 30,005+ 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.