让 ActiveModel::Callbacks 与 ActiveResource 一起使用
我正在尝试让 ActiveModel::Callbacks 与 Rails 3 应用程序的 ActiveResource (特别是 after_initialize)一起使用,但我似乎无法让它工作。我没有收到任何错误,但回调方法从未执行。
这是一段代码
class User < ActiveResource::Base
extend ActiveModel::Callbacks
define_model_callbacks :initialize, :only => :after
after_initialize :update_info
def update_info
puts 'info'
end
end
由于某种原因, update_info 永远不会被执行。有人知道如何让它发挥作用吗?
I am trying to get ActiveModel::Callbacks to work with ActiveResource (specifically after_initialize) for a Rails 3 app, but I can't seem to get it to work. I don't get any errors, but the callback method is never executed.
Here is a snippet of code
class User < ActiveResource::Base
extend ActiveModel::Callbacks
define_model_callbacks :initialize, :only => :after
after_initialize :update_info
def update_info
puts 'info'
end
end
For some reason, the update_info is never executed. Anyone have any idea how to get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有人感兴趣,我重新阅读了有关此的文档,我认为是对代码如何在幕后工作的解释,结果是一个要求,表明我需要重写我添加回调的方法to:
这对我来说似乎非常违反直觉,因为它希望您追踪现有方法的签名,覆盖它并添加回调功能。我希望我在这里遗漏了一些东西,并且只是犯了一个错误,但我还没有找到任何其他解决方案。
无论如何,这里有一个猴子补丁,可以为所有 AR 类提供此回调:
In case anyone is interested, I re-read the documentation on this, and what I thought was an explanation of how the code worked under the covers, turned out to be a requirement which stated that I needed to override the method I was adding callbacks to:
This seems incredibly counter-intuitive to me, as it expects you to track down the signature of the existing method, overwrite it, and add the callback functionality. I hope I am missing something here, and simply making a mistake, but I haven't gotten any other solution to work.
Anyways, here is a monkey patch to provide this callback to all AR classes: