proxy_association 查找未关联记录的说明 [英] Explanation of proxy_association to find unassociated records

查看:11
本文介绍了proxy_association 查找未关联记录的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到了一些魔法,我希望能得到一些帮助来理解它,这样我就可以编写明智的代码.

I came across some magic today and I am hoping for some help in understanding it so I can write informed code.

在我的应用中,我有三个类:

In my app, I have three classes:

class Person < ActiveRecord::Base
  has_many :selected_apps
  has_many :app_profiles, through: :selected_apps do
    def unselected(reload=false)
      @unselected_app_profiles = nil if reload
      @unselected_app_profiles ||= proxy_association.owner.app_profile_ids.empty? ?
        AppProfile.all :
        AppProfile.where("id NOT IN (?)", proxy_association.owner.app_profile_ids)
    end
  end
end

class AppProfile < ActiveRecord::Base
end

class SelectedApp < ActiveRecord::Base
  belongs_to :person
  belongs_to :app_profile
end

上面的代码让我可以执行 person.app_profiles.unselected 并取回所有当前未与 Person 关联的 AppProfiles无需做大量的 SQL 工作.太棒了!

The above code lets me do person.app_profiles.unselected and get back all of the AppProfiles that are not currently associated with the Person without having to do a lot of SQL work. Brilliant!

我的问题是我不理解代码 - 这总是让我感到不安.我尝试浏览 proxy_association 文档,但它相当不透明.

My problem is that I don't understand the code - which always leaves me feeling unsettled. I tried trolling through the proxy_association documentation, but it was fairly opaque.

谁能提供合理直接的解释和/或了解更多信息的好地方?

Can anyone provide a reasonably straight-forward explanation and/or a good place to learn more?

推荐答案

基本上,当你在扩展一个 association 时调用 self 它不会返回一个 关联 实例,而是委托给 to_a.

Basically, when you call self while extending an association it won't return an Association instance, but instead delegates to to_a.

试试看:

class Person < ActiveRecord::Base
  has_many :app_profiles, through: :selected_apps do
    def test_me
      self
    end
  end
end

有时我们需要在扩展关联本身的同时获取实际的association 对象.输入 ownertargetreflection 属性.

Sometimes we need to get to the actual association object while were extending the association itself. Enter the proxy_association method, which will give us the association which contains the owner, target, and reflection attributes.

这里的参考是文档.

这个问题提供了一个更简单的用例proxy_association.owner.

This question provides a simpler use case of proxy_association.owner.

这篇关于proxy_association 查找未关联记录的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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