Rails 3“未定义方法”关联代理中
我有一个模型,其中添加了几个辅助实例方法。一个非常人为的示例:
class Post < ActiveRecord::Base
...
def permalink
"http://some_url.com/p/#{id}"
end
end
class Notification < ActiveRecord::Base
belongs_to :post
...
end
另外,我有一个 Resque 队列,用于离线处理作业。当我想通过关联(如通知)调用 Resque 工作线程中的“永久链接”实例方法时,就会出现问题。假设这里是在我的 Resque 任务中运行的代码:
post = Notification.find(1234).post
do_something_with_string(post.permalink)
问题是引用 post.permalink barfs:
NoMethodError: undefined method `permalink' for "#<Post:0xblahblahblah>":Post
at blahblahblah/activerecord-3.0.7/lib/active_record/associations/association_proxy.rb:216:in `method_missing'
我收集到这里发生了一些 ActiveRecord 魔法,以及当我说 Notification.find(1234) 时我得到的结果。 post是一个代理对象(AssociationProxy)。但我已经尝试了几种方法来使其发挥作用,但无法实现。我可能遗漏了一些明显的东西,但到目前为止,这似乎是 ActiveRecord 对我的模型做的一件非常愚蠢的事情。我需要对我的模型做一些神奇的事情才能让 Ruby 实例方法等基本功能在它们上正常工作吗?
我唯一能想到的就是用 after_initialize 填充模型中的实例变量,然后将 attr_reader 添加到模型中以使关联代理了解发生了什么。但这似乎完全是一个拼凑。
I've got a model that I've added a couple of helper instance methods to. A very contrived example:
class Post < ActiveRecord::Base
...
def permalink
"http://some_url.com/p/#{id}"
end
end
class Notification < ActiveRecord::Base
belongs_to :post
...
end
Also, I've got a Resque queue that I'm using to process jobs offline. The problem arises when I want to call my "permalink" instance method in my Resque worker through an association, like a notification. Let's say here's the code running in my Resque task:
post = Notification.find(1234).post
do_something_with_string(post.permalink)
The problem is that referencing post.permalink barfs:
NoMethodError: undefined method `permalink' for "#<Post:0xblahblahblah>":Post
at blahblahblah/activerecord-3.0.7/lib/active_record/associations/association_proxy.rb:216:in `method_missing'
I've gathered that some ActiveRecord magic is happening here, and what I'm getting back when I say Notification.find(1234).post is a proxy object (AssociationProxy). But I've tried several things to get this to work, and am unable to. I'm probably missing something obvious, but so far this seems like a pretty stupid thing for ActiveRecord to be doing to my model. Is there some magic thing I need to do to my models to have basic things like Ruby instance methods work properly on them?
The only thing I can think to try is to populate instance variables in the model with after_initialize and then add attr_reader to the model to get the association proxy to realize what's going on. But that seems like quite a kludge.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您提到此代码正在 Resque 工作线程中运行。添加
permalink
方法后,您还需要确保并重新启动您的Resque工作线程。重新启动 Rails 服务器不会为您执行此操作 - 您需要手动终止/重新启动 Resque 进程。You mentioned that this code is running in a Resque worker. After you added the
permalink
method, you need to make sure and restart your Resque workers too. Restarting your rails server does not do this for you -- you need to manually kill/restart your Resque processes.