I have an action that simply toggles the #active
attribute to the opposite boolean state:
@blog.active == true
then update
it to inactive@blog.active == false
then update
it to activeI 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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With