Ruby on rails 关于查找未关联记录的代理关联的说明

Ruby on rails 关于查找未关联记录的代理关联的说明,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,今天我遇到了一些魔术,我希望能得到一些帮助来理解它,这样我就可以编写有见地的代码了 在我的应用程序中,我有三个类: 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 rel

今天我遇到了一些魔术,我希望能得到一些帮助来理解它,这样我就可以编写有见地的代码了

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

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
class-Person
上面的代码允许我执行
person.app\u profiles.unselected
,并返回当前未与
person
关联的所有
AppProfiles
,而无需执行大量SQL工作。太棒了

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


任何人都能提供一个合理直接的解释和/或一个学习更多信息的好地方吗?

基本上,当您在扩展
关联时调用
self
时,它不会返回
关联
实例,而是将
委托给a

试试看:

class Person < ActiveRecord::Base
  has_many :app_profiles, through: :selected_apps do
    def test_me
      self
    end
  end
end
class-Person
有时,在扩展关联本身时,我们需要获得实际的
关联
对象。输入,这将为我们提供
关联
,其中包含

以下是参考资料


提供了一个更简单的
代理\u关联的用例。所有者

谢谢你,Azolo!有用的帖子和链接-我将学习。。。干杯