对于proxy_owner在ActiveRecord的替代方法 [英] Alternative method for proxy_owner in ActiveRecord

查看:82
本文介绍了对于proxy_owner在ActiveRecord的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ActiveRecord的proxy_owner现在是很precated这里的解释很含糊如何去改变它,所以我不知道如何使用它我的情况:   http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy

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

下面是我想要做什么:

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

我得到一个警告,当我运行此$ C C的proxy_owner $是pcated德$ P $:

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.

我可以代替proxy_owner.author有:

I can replace proxy_owner.author with:

@associaton.owner.author

本作品;然而,似乎危险。我失去了一些东西呢?

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

推荐答案

我认为这是比较安全的发送:所有者 proxy_association 来代替:

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

使用 proxy_association 目前在<一提到href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Association+extensions">documentation:

不过,里面的实际扩展code,您将无法访问   记录(record.association(:项目).owner)同上。在这种情况下,您可以访问proxy_association。   例如,record.association(:项)和   record.items.proxy_association将返回相同对象,允许   你做出像proxy_association.owner内部关联电话   扩展。

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.

这篇关于对于proxy_owner在ActiveRecord的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆