How to toggle a Boolean attribute in a controller action

Active Record's toggle and toggle! methods handle toggling a Boolean attribute:

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

toggle changes the attribute, but doesn't save the change to the database (so a separate call to save or save! is needed).

toggle! changes the attribute and saves the record, but bypasses the model's validations.


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