首页 文章

如何在Rails中的每次访问中触发Model方法

提问于
浏览
0

我有一个模型,每次从它访问数据或保存到它时都需要触发一个方法 . 我很难搞清楚如何触发该方法 .

这是我尝试过的:

class MyModel < ActiveRecord::Base

    after_initialize :hello
    def hello
        binding.pry
    end
end

我的理解是,只要访问此模型,after_initialize就会触发,但显然情况并非如此 . 如何通过以下呼叫触发此操作:

@instance = MyModel.paginate()

3 回答

  • 0

    Rails没有提供通常可以在这样的操作中访问的方式,但是对于单个情况,它确实可以做类似的事情

    class MyModel < ActiveRecord::Base
        #all cases that wanna include
        before_save :hello
        after_save :hello
        after_initialize :hello
        def hello
            binding.pry
        end
    end
    

    检查来自documentation的可用回调

  • 0

    after_initialize 在创建实例后触发,而不是在访问实例时触发 . 实际上,这是什么意思"it is accessed"?

    如果你的意思是在调用任何对象方法或调用持久性方法时,它会产生很大的不同 .

    根据您的需要,您可能希望使用Proxy对象 . 您可以将实例封装在获取调用的Proxy中,记录要记录的内容,然后调用该对象 . 否则,你需要覆盖/猴子补丁类中的所有方法,这绝对不是一个好主意 .

    @instance = MethodLogger.new(@instance)
    @instance.paginate
    
  • 0

    这是所有 callbacks 的清单

    after_initialize, after_find, after_touch, before_validation, after_validation,
      before_save, around_save, after_save, before_create, around_create,
      after_create, before_update, around_update, after_update,
      before_destroy, around_destroy, after_destroy, after_commit, after_rollback
    

    您可以使用任何这些回调触发您的方法 . 查看示例

    class MyModel < ActiveRecord::Base
    
       after_find :hello
       after_save :hello
       # call_back goes here ...
    
       def hello
          binding.pry
       end
    end
    

    after_initialize 在实例化新对象后被触发,例如

    MyModel.new()
    

相关问题