开发者

Rails 3 "undefined method" in association proxy

开发者 https://www.devze.com 2023-03-08 02:32 出处:网络
I\'ve got a model that I\'ve added a couple of helper instance methods to. A very contrived example: class Post < ActiveRecord::Base

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 p开发者_C百科rocess 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消