2011-11-18 39 views
0

我正在为Ruby on Rails 3中的用户创建操作跟踪。我想在控制器中使用after_filter方法,但我不知道如何在我的action_tracking方法中获取当前对象或当前操作。任何解决方案Ruby on Rails - 如何在after_filter中获取已更改的对象?

# some_controller.rb 
class SomeController < ApplicationController 
    after_filter :action_tracking, only: [ :create, :update, :delete ] 
    ... 
end 

# application_controller.rb 
class ApplicationController < ActionController::Base 
    def action_tracking 
    action = <get name of action> # create, update or delete... 
    <object> = <get changed object> # event, user... 
    changes = <object>.changes  # { 'title' => ["Title", "New Title"] } 
    <object>.tracking.create(action, changes) 
    end 
end 

回答

0
def action_tracking 
    action = params[:action] 
    changes = changed_object.changes 
    changed_object.tracking.create(action, changes) 
end 

# override for each controller 
# there is no way to know this in a generic way, unless you use something 
# like inherited_resources, or active scaffold, where the objects is "known" 
def changed_object 
    @user 
end 
+0

THX,它的工作原理,但其值'changes'总是空的。是因为我在保存后调用它(保存'changes'重置)。是否可以修复,而无需向'some_controller'动作添加更多代码? –

+0

是的,保存“变更”后重置。我会说最好的方法来做到这一点(我之前做过这种事情)是将逻辑放在回调或观察者中的模型中,然后传递动作名称。在这种情况下(回调或观察者),更改散列尚未重置。 – clyfe

+0

我试图添加跟踪到模型,但模型没有访问一些变量(如'params []'..),我需要。我不知道你的意思(回叫或观察者),你可以发表一些关于它的文章的链接? –

相关问题