2009-08-17 7 views
1

after_updateを使用して変更を記録するモデルがあります。このロギングメカニズムを有効にせずにモデルを変更したい場合があります。 after_updateにパラメータを渡す方法はありますか、それをすべてスキップしますか?after_updateコールバックをスキップ

私はこれにはいい解決策がありたいと思いますし、それについてもっと良い方法があれば、after_updateを削除するつもりです。

答えて

3

私はモデルにブール値を追加する方法を提案しましたが、更新後にフラグを設定してクリアする方法を書いています。例えばその後

def without_logging_changes_to(model) 
    # store current value of the flag so it can be restored 
    # when we leave the block 
    remembered_value = model.log_update 
    model.log_update = false 
    begin 
    yield 
    ensure 
    model.log_update = remembered_value 
    end 
end 

それを使用する:

あなたは彼らがsendメソッドを通じて呼び出すことができる民間のActiveRecord方法

update_without_callbacks 
create_without_callbacks 

を使用することができますRailsの2で

without_logging_changes_to my_model do 
    my_model.update_attributes(updates) 
end 
+0

これは私がやったことですが、それはハックを感じます。レールを使って周りに道がないと思います。 – Ori

+0

もっと洗練された解決策が見つかったら教えてください。ありがとう。 – mikej

0

log_last_updateなどのブール値をモデルに追加して、after_updateコールバックで確認することができます。

0
class MyModel < ActiveRecord::Base 

    after_update :do_something 

    attr_accessor :should_do_something 



    def should_do_something? 
    should_do_something != false 
    end 

    def do_something 
    if should_do_something? 
     ... 
    end 
    end 

end 


y = MyModel.new 
y.save! # callback is triggered 

n = MyModel.new 
n.should_do_something = false 
n.save! # callback isn't triggered 
0

# Update attributes on your model 
your_model.some_attribute = some_value 

# Update model without callbacks 
your_model.send(:update_without_callbacks) 
関連する問題