Don't use proxy_target in AR association extensions
August 21st, 2008
This is as much a note to my future self as a warning post to others doomed to make the same mistake I did. I was creating a few methods to extend a has_many association with. Based on the current Rails docs I used the proxy_target accessor to get at the records of the association.
The only problem with that is proxy_target is not populated unless the association had previously been traversed through the same model instance. After I tossed in a line of code into the method that explicitly loaded the association I decided this was a bug in Rails.
It wasn’t a bug
I started thinking about a patch but decided this couldn’t possibly have been missed that long. So instead I googled quite a bit more and eventually found “Should proxy_owner be eager loaded?”. This accurately described my issue.
The answer
Put simply, proxy_target is implied in the scope of association extensions. Here’s some of my own example code that demonstrates:
Also, if you go off the beaten path in the Rails docs a bit you’ll find this behavior is documented in ActiveRecord::Associations::AssociationProxy. This should probably be mentioned in ActiveRecord::Associations::ClassMethods where proxy_target is discussed. Maybe I’ll make my first doc patch tomorrow.
Feel free to use the comments to ridicule me.
1 Response to “Don't use proxy_target in AR association extensions”
Sorry, comments are closed for this article.
August 27th, 2008 at 12:44 AM
Thanks - I too was trying to force the proxy_target to load the associated records. This works much better!