Rails에서 타임스탬프 전환 간소화

발행: (2026년 2월 25일 오전 02:15 GMT+9)
2 분 소요
원문: Dev.to

Source: Dev.to

Overview

저는 completed_at 같은 타임스탬프를 부울 플래그처럼 자주 사용합니다. 실제 부울보다 약간 더 많은 (메타) 데이터를 제공하지만, UI에서는 일반적으로 날짜‑시간 필드 대신 사용자가 토글할 수 있는 체크박스를 보여주고 싶습니다.

Implementation

간단한 Concern가 다음과 같은 API를 제공합니다:

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

그런 다음 폼에서 form.check_box :completed를 사용할 수 있습니다.

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

이처럼 작은 Concern들이 여러분의 삶을 조금 더 편하게 만들어 줍니다.

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

0 조회
Back to Blog

관련 글

더 보기 »

importmap-rails 이해하기

소개 만약 최신 JavaScript를 사용해 본 적이 있다면, ES modules와 import statements에 익숙할 것입니다. Rails 앱은 이를 위해 esbuild, vite, 또는 bun을 사용할 수 있습니다.

GitHub README에 Credly 인증서 전시하기

개요: Credly에 인증서가 있고 이를 GitHub 프로필에 표시하고 싶다면, 오픈‑source 도구가 이를 매우 간단하게 만들어 줍니다. 이 도구는 무료 API를 제공합니다.