Ask A Question


You’re not receiving notifications from this thread.

Switch state of boolean field

Benny Maas asked in General


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.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,038+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.