2016-03-29 13 views
0

の属性。私は定期的な更新と作成でも計算を実行できるようにしたい。オーバーライドタイムスタンプは、私は次のようにタイムスタンプ属性をオーバーライドしていますActiveRecordのモデルのユーザーを持っているActiveRecordのモデル

例:

User.create 
User.update_attributes(:not_timestamp_attributes => <some value>) 

も計算してタイムスタンプを更新する必要があります。

この問題を回避するためのベストプラクティスはありますか?私はグーグルで、タイムスタンプの属性を上書きすることで何も見つけることができませんでした。

答えて

1

ベストプラクティスは、ActiveRecordでこれらの値の更新を処理させることです。

しかし、あなたはまだ、このような何かを明示的にそれを行うためにbefore_savebefore_createにいくつかのコールバックを追加してみてください可能性があり、計算のいくつかの並べ替えを行う必要がある場合:

class User < ActiveRecord::Base 
    before_save :compute_updated_at 
    before_create :compute_created_at, :compute_updated_at 

    def created_at 
    read_attribute(:created_at) 
    end 

    def created_at=(value) 
    compute_created_at 
    end 

    def updated_at 
    read_attribute(:updated_at) 
    end 

    def updated_at=(value) 
    compute_updated_at 
    end 

    private 

    def compute_updated_at 
    write_attribute(:updated_at, Time.now + 1.month) 
    end 

    def compute_created_at 
    write_attribute(:created_at, Time.now + 2.month) 
    end 
end 
0

は、あなたの計算のために別の列を使用することができます値はbefore_saveのアクションとActiveRecord::Dirtyの "column_changed?"を使用してシステムの更新された値を返します。方法

before_save :calculate_created_at, if: :created_at_changed? 

def calculate_created_at 
    update_column(:calculated_created_at, created_at - 1.days) 
end 
関連する問題