0

我正在尝试为所有 CRUD 操作创建数据库日志。我知道我可以转到每个控制器操作并插入方法以使其工作。有没有办法更优雅地做到这一点,以便在 CRUD 操作发生之前为所有控制器调用方法。这些是我正在使用的方法:

创建交易

TransactionLog.create(:contact_id => contact_id) #Create the transaction
    

创建变更日志

def self.start_logging(current_user, data, action, new_content ={}, old_content ={}, transaction_log_id)
  @log = ChangeLog.new(:table => data, :action => action, :new_content => new_content.to_json, :old_content => old_content.to_json, :transaction_log_id => transaction_log_id)
  @log.save
end
4

3 回答 3

1

尝试使用过滤器(请参阅此处的第 8 节:http: //guides.rubyonrails.org/action_controller_overview.html

于 2013-07-01T17:20:29.057 回答
0

before_filter 的想法是要走的路。其他答案中缺少的是如何将其应用于所有控制器。最好的选择是使用定义和激活过滤器的代码创建一个 mixin。

module HasCrudFilter
  def self.included(base)
    base.class_eval do
      before_filter :my_filter, only: [:create, :update, :destroy]

      def my_filter
        #  Your code here...
      end
    end
  end
end

然后在你的控制器中

class MyModelController < ApplicationController
  include HasCrudFilter
end
于 2013-07-01T17:54:12.620 回答
0

你可以做

before_filter :your_method, only: ['create', 'update' 'destroy']

def your_method
  #do the things
end
于 2013-07-01T17:41:10.027 回答