The project is in a healthy, maintained state
Adds methods like user.admin! that toggle boolean attributes with validations and callbacks, unlike Rails toggle! which bypasses them.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

 Project Readme

acts_as_togglable

Gem Version

Named bang toggle methods for ActiveRecord boolean attributes.

Instead of user.toggle!(:admin) (which bypasses validations), get clean named methods like user.admin! that run validations and callbacks.

Installation

Add to your Gemfile:

gem "acts_as_togglable"

Usage

Explicit mode

Specify which boolean attributes get bang methods:

class User < ApplicationRecord
  acts_as_togglable :admin, :active
end

user = User.create(admin: false, active: true)
user.admin!   # => true  (toggled and saved)
user.active!  # => false (toggled and saved)
user.admin!   # => false (toggled back)

Auto mode

Generate bang methods for all boolean columns:

class Post < ApplicationRecord
  acts_as_togglable
end

post = Post.create(published: false, featured: true)
post.published!  # => true
post.featured!   # => false

How it works

Each bang method:

  • Toggles the boolean value
  • Saves with update! (runs validations and callbacks)
  • Returns the new boolean value
  • Raises ActiveRecord::RecordInvalid if validations fail

Why not just use toggle!?

Rails' built-in toggle! bypasses validations and callbacks. This matters when your app depends on them.

For example, a blog post that updates the sitemap when published:

class Post < ApplicationRecord
  acts_as_togglable :published

  after_save :update_sitemap, if: :published?

  private

  def update_sitemap
    SitemapGenerator.rebuild
  end
end
# With toggle! — callback is SKIPPED, sitemap not updated
post.toggle!(:published)

# With acts_as_togglable — callback fires, sitemap updated
post.published!

Other cases where callbacks and validations matter:

  • Sending a welcome email when a user is activated
  • Logging an audit trail when permissions change
  • Validating that only one post can be featured at a time

Comparison with Rails toggle!

acts_as_togglable Rails toggle!
Syntax user.admin! user.toggle!(:admin)
Validations Runs Bypassed
Callbacks Runs Bypassed
Return value New boolean true

License

MIT