Simplifying timestamp toggles in Rails

Published: (February 24, 2026 at 12:15 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Overview

I often use timestamps, like completed_at, as a boolean flag. It offers a bit more (meta) data than a real boolean, but on the UI you typically want to show a checkbox that a user can toggle instead of a datetime field.

Implementation

A simple concern provides an API such as:

@resource.completed?
@resource.complete!
@resource.complete=

You can then use form.check_box :completed in your forms.

Boolean attribute concern

# lib/boolean_attributes.rb
module BooleanAttribute
  extend ActiveSupport::Concern

  class_methods do
    def boolean_attribute(*fields)
      fields.each do |field|
        column = :"#{field}_at"

        define_method(field) { public_send(column).present? }

        define_method("#{field}?") { public_send(column).present? }

        define_method("#{field}=") do |value|
          public_send(
            "#{column}=",
            ActiveModel::Type::Boolean.new.cast(value) ? Time.current : nil
          )
        end

        define_method("#{field}!") { update!("#{column}": Time.current) }
      end
    end
  end
end

Using the concern in a model

class Task < ApplicationRecord
  include BooleanAttributes

  boolean_attribute :completed

  # …
end

Conclusion

It’s these small concerns that make your life a bit easier.

Original article published on Rails Designer’s Build a SaaS Blog.

0 views
Back to Blog

Related posts

Read more »

Stop Using .any? the Wrong Way in Rails

Introduction A single block passed to .any? can silently load thousands of records into memory—no warnings, no errors, just unnecessary objects. Most Rails dev...

Understanding importmap-rails

Introduction If you've worked with modern JavaScript, you're familiar with ES modules and import statements. Rails apps can use esbuild or vite or bun for this...