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

时间:2012-05-01 22:27:08

标签: 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 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获取当前未与AppProfiles相关联的所有Person,而无需执行大量SQL工作。辉煌!

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

任何人都可以提供合理直接的解释和/或了解更多信息的好地方吗?

1 个答案:

答案 0 :(得分: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

有时我们需要在扩展关联本身时访问实际的association对象。输入proxy_association method,这将为我们提供包含owner, target, and reflection attributesassociation

此处参考的是documentation

This question提供了proxy_association.owner的简单用例。

相关问题