All threads / Switch state of boolean field

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Switch state of boolean field

Benny Maas asked in General

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.