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

관련 글

더 보기 »

솔로 프론트엔드 팀: Pure Ruby로 UI 시스템 구축

'Partial' 문제 우리는 Rails를 사랑합니다. ERB도 사랑합니다. 하지만 솔직히 말해서, app/views는 보통 어떤 Rails 코드베이스에서도 가장 지저분한 부분입니다. 처음엔 간단하게 시작합니다. 그런데…

FSCSS 변수 대체 연산자 (||)

FSCSS Variable Fallback Operator의 커버 이미지 ||https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fd...