0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsの_wasメソッドについて

Posted at

Railsの_wasメソッドについて知っておきたいこと

はじめに

RailsのActiveRecordには_wasという便利なメソッドがあります。このメソッドは、モデルの属性値の変更を追跡する際に非常に役立ちます。

_wasメソッドとは

_wasメソッドは、ActiveRecordの属性の変更を追跡する機能の一部です。データベースから読み込まれた時点での値(元の値)を保持し、その属性が変更された後でも元の値を参照することができます。

使用できる場面

1. バリデーションでの使用

購入日時の変更を検証する例:

class Order < ApplicationRecord
  validate :purchase_date_changed?, on: :update

  private

  def purchase_date_changed?
    if purchased_at_was == purchased_at
      errors.add(:purchased_at, '購入日時が変更されていません')
    end
  end
end

2. コールバックでの使用

商品の価格変更を記録する例:

class Product < ApplicationRecord
  before_save :log_price_change

  private

  def log_price_change
    if price_was != price
      PriceChangeLog.create!(
        product_id: id,
        old_price: price_was,
        new_price: price,
        changed_at: Time.current
      )
    end
  end
end

3. 変更の追跡

注文ステータスの変更を通知する例:

class Order < ApplicationRecord
  after_save :notify_status_change

  private

  def notify_status_change
    if status_was != status
      NotificationService.status_changed(
        order_id: id,
        old_status: status_was,
        new_status: status,
        user_id: user_id
      )
    end
  end
end

使用例:配送システム

配送予定日の変更を管理する例:

class Delivery < ApplicationRecord
  validate :validate_delivery_date_change

  private

  def validate_delivery_date_change
    if scheduled_date_was.present? && scheduled_date_was > Date.current
      if scheduled_date < scheduled_date_was
        errors.add(:scheduled_date, '配送予定日は前倒しできません')
      end
    end
  end
end

まとめ

_wasメソッドは以下のような場面で特に有用です:

  • 属性値の変更を検証する必要がある場合
  • 変更履歴を記録する必要がある場合
  • 変更前後の値に基づいて処理を分岐させる必要がある場合

このメソッドを活用することで、より堅牢なアプリケーションの開発が可能になります。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?