高效收集模特的所有(伟大的)大孩子

时间:2016-07-29 19:35:34

标签: ruby-on-rails activerecord

我有一个团队模型,如下所示:

class Team < ActiveRecord::Base
  has_many :applications
  has_many :interests, through: :applications
  has_many :indications, through: :interests
end

我有一个如下所示的Indication模型:

class Indication < ActiveRecord::Base
   belongs_to :interest
   belongs_to :application
   belongs_to :team

   scope :open, -> {where(selection_stages_id: nil, selection_statuses_id: nil)}

end

我可以看到一个用例,其中我可能有多个团队的集合,我希望有一个可以与它们链接的所有指示的集合。

  ####example
  teams = Team.all
  associated_indications = teams.collect(&:indications)
  # => [#<ActiveRecord::Associations::CollectionProxy [#<Indication id: 1, selection_stages_id: nil, selection_statuses_id: nil, interest_id: 2, created_at: "2016-07-26 23:51:36", updated_at: "2016-07-27 15:20:12">]>] 

   ### I would like to do this:
   #1# associated_indications.find(1)
   # ==> #<Enumerator: [#<ActiveRecord::Associations::CollectionProxy [#<Indication id: 1, selection_stages_id: nil, selection_statuses_id: nil, interest_id: 2, created_at: "2016-07-26 23:51:36", updated_at: "2016-07-27 15:20:12">]>]:find(1)> 
   #2# associated_indications.include?(Indication.find(1))
   # ==> false


 #for comparison, 
 Team.all.find(1).indications
 # ==> #<ActiveRecord::Associations::CollectionProxy [#<Indication id: 1, selection_stages_id: nil, selection_statuses_id: nil, interest_id: 2, created_at: "2016-07-26 23:51:36", updated_at: "2016-07-27 15:20:12">]>
 # This following line throws an error
 Team.all.indications
 # ^ Holy Grail

有什么想法吗?如果你做到这一点,我感谢你的耐心等待。

1 个答案:

答案 0 :(得分:0)

怎么样

teams = Team.all
indications = Indication.joins(interest: { application: :team }).where(teams: { id: teams.pluck(:id) })

它只有2个查询,并且指示仍然是ActiveRecord关系。