2017-08-01 53 views

回答

1

你可以有一個GenericModule,包括這在任何模型,你希望

module GenericModule 
    extend ActiveSupport::Concern 

    included do 
    after_create :log_creation 
    end 

    def log_creation 
    # perform logging 
    end 
end 

和模型

class User < ActiveRecord::Base 
    include GenericModule 

    # ...other model code... 
end 

你可以爲您需要此行爲的所有模型提供此功能。

+0

模塊是否在lib中? – PiKaY

+0

@PiKaY https://stackoverflow.com/questions/4013486/ruby-on-rails-where-should-i-store-modules – Kavincat

+0

@Kavincat謝謝。 – PiKaY

0

從Ruby on Rails的指南上ActiveRecord Callbacks

活動記錄能夠創建封裝回調方法的類,所以它變得非常容易重用他們。

下面是一個例子,我們創建一個類與after_destroy回調的PictureFile型號:

class PictureFileCallbacks 
    def after_destroy(picture_file) 
    if File.exists?(picture_file.filepath) 
     File.delete(picture_file.filepath) 
    end 
    end 
end 

一個類的內部聲明時,如上述,回調方法將接收模型對象作爲參數。現在,我們可以使用回調類模型:

class PictureFile < ActiveRecord::Base 
    after_destroy PictureFileCallbacks.new 
end 
相關問題