Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle a Boolean attribute in a controller action

I have an action that simply toggles the #active attribute to the opposite boolean state:

  • If @blog.active == true then update it to inactive
  • If @blog.active == false then update it to active

I got the following custom action in a controller to work, but there has to be some Rails way to more elegantly do this:

class BlogsController < ApplicationController

  ...    

  def toggle_active
    if @blog.active?
      @blog.update(active: false)
    else
      @blog.update(active: true)
    end
  end

end

Is there a Rails way of updating a boolean attribute to the opposite boolean state?

like image 961
Neil Avatar asked Nov 15 '16 22:11

Neil


People also ask

How do I toggle a Boolean in Javascript?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do I toggle a value in Javascript?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.


1 Answers

ActiveRecord has the toggle and toggle! methods which do this. Just keep in mind that the toggle! method skips validation checks.

class BlogsController < ApplicationController

  ...    

  def toggle_active
    @blog.toggle!(:active)
  end

end

If you want to run validations you can do

@blog.toggle(:active).save

You can read the source code for the methods here

like image 66
robertoplancarte Avatar answered Oct 05 '22 08:10

robertoplancarte