proxy_association的说明,用于查找无关联的记录

jvi*_*ian 4 activerecord ruby-on-rails

我今天遇到了一些魔法,我希望能帮助你理解它,这样我才能编写有用的代码.

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

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
Run Code Online (Sandbox Code Playgroud)

上面的代码让我可以做到person.app_profiles.unselected并取回AppProfiles当前没有与之相关的所有内容,Person而无需进行大量的SQL工作.辉煌!

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

任何人都可以提供一个相当直接的解释和/或一个学习更多的好地方吗?

Azo*_*olo 10

基本上,当您self在扩展时调用association它不会返回Association实例,而是委托给to_a.

试试吧:

class Person < ActiveRecord::Base
  has_many :app_profiles, through: :selected_apps do
    def test_me
      self
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

有时我们需要association在扩展关联本身的同时找到实际对象.输入proxy_association,这将给我们的association其中包含owner,targetreflection属性.

这里是参考文档.

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