acts_as_togglable
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! # => falseHow it works
Each bang method:
- Toggles the boolean value
- Saves with
update!(runs validations and callbacks) - Returns the new boolean value
- Raises
ActiveRecord::RecordInvalidif 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