Alternative method for proxy_owner in ActiveRecord
Asked Answered
P

1

4

ActiveRecord proxy_owner is now deprecated and the explanation here is very vague on how to change it, so I'm not sure how to use it my case: http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy

Here is what I'm trying to do:

class Library < ActiveRecord::Base
  has_many :books do
    def some_method
      proxy_owner.author
    end
  end
end

I get a warning when I run this code that proxy_owner is deprecated:

DEPRECATION WARNING: Calling record.books.proxy_owner is deprecated. Please use record.association(:books).owner instead.

I can replace proxy_owner.author with:

@associaton.owner.author

This works; however, it seems dangerous. Am I missing something here?

Partan answered 9/8, 2011 at 19:27 Comment(0)
M
18

I think it's safer to send :owner to proxy_association instead:

class Library < ActiveRecord::Base
  has_many :books do
    def some_method
      proxy_association.owner.author
    end
  end
end

The use of proxy_association is now mentioned in the documentation:

However, inside the actual extension code, you will not have access to the record (record.association(:items).owner) as above. In this case, you can access proxy_association. For example, record.association(:items) and record.items.proxy_association will return the same object, allowing you to make calls like proxy_association.owner inside association extensions.

Monosaccharide answered 9/9, 2011 at 10:40 Comment(2)
This is what I expected as well, but it doesn't seem to work. I get an undefined method "proxy_association" error.Plexor
The previous comment applies to Rails 3.0. "proxy_owner" is fine in Rails 3.0. It's deprecated in Rails 3.1, though, and in Rails 3.1, Dave Nolan's answer is correct.Plexor

© 2022 - 2024 — McMap. All rights reserved.