2014-11-14 58 views
0

所以我有一個對象,我想定義一個生命週期掛鉤,如before_create,after_create等定義自定義對象生命週期的鉤子紅寶石

我想打電話給這個after_retire並將它安裝,所以我可以做以下:

class User < ActiveRecord::Base 
    include Active 
    after_retire :method 

    def method 
    #do stuff 
    end 
end 

到目前爲止,我有一個模塊的設置,像這樣,但我不斷收到一個未定義的方法在我的用戶模型after_retire錯誤。

module Active 
    extend ActiveSupport::Concern 

    included do 
    define_callbacks :retire 
    set_callback :retire, :after, :after_retire 
    default_scope { where(:retired => false) } 
    scope :retired, where(:retired => true) 
    end 

    def retire! 
    run_callbacks :retire do 
     update_attribute :retired, true 
     update_attribute :retired_at, Time.now.to_datetime 
    end 
    end 
end 

我該如何設置它?

回答

1

before/after_callback語法通過#define_model_callbacks在ActiveModel :: Callbacks中處理。原始的ActiveSupport ::回調會要求您使用#set_callback沒有任何語法糖:

module Active 
    extend ActiveSupport::Concern 

    included do 
    define_callbacks :retire 
    default_scope { where(:retired => false) } 
    scope :retired, where(:retired => true) 
    end 

    def retire! 
    run_callbacks :retire do 
     update_attribute :retired, true 
     update_attribute :retired_at, Time.now.to_datetime 
    end 
    end 
end 

class User < ActiveRecord::Base 
    include Active 
    set_callback :retire, :after, :method 

    def method 
    #do stuff 
    end 
end 

如果你想有後/語法之前,因爲你是用一個ActiveRecord工作(並因此加載ActiveModel)類,您可以使用:

module Active 
    extend ActiveSupport::Concern 

    included do 
    define_model_callbacks :retire 
    default_scope { where(:retired => false) } 
    scope :retired, where(:retired => true) 
    end 

    def retire! 
    run_callbacks :retire do 
     update_attribute :retired, true 
     update_attribute :retired_at, Time.now.to_datetime 
    end 
    end 
end 

class User < ActiveRecord::Base 
    include Active 
    after_retire :method 

    def method 
    #do stuff 
    end 
end 
+1

此外,您應該使用update_attributes(retired:true,retired_at:Time.now)以避免不必要的額外數據庫調用。 – 2014-11-14 23:44:35