【问题标题】:How to retrieve all related objects from an existing selection set in Rails如何从 Rails 中的现有选择集中检索所有相关对象
【发布时间】:2016-11-13 10:16:18
【问题描述】:

在 Rails 应用程序中,我有两个模型,它们通过 has_manybelongs_to 关联关联:

class Entity < ActiveRecord::Base
  has_many :applicants
end
class Applicant < ActiveRecord::Base
  belongs_to :entity
end

我使用 SearchKick 来首先选择一些实体 - 这并不重要,但 鉴于现有的实体对象集合,我如何检索所有相关的申请人对象?

# select some entities (in my app I'm using SearchKick to run the search)
entities = Entity.search params[:query]

# now find the applicants related to the selected entities
applicants = entities.???

这可行,但考虑到大量选择,速度很慢:

# retrieve the applicants related to the selected entities
applicants = []
entities.each do |entity|
  applicants += entity.applicants
end

是否有 Rails 速记来检索与所选实体相关的申请人?

我尝试过的其他事情:

entities.class => Entity::ActiveRecord_Relation 
entities.applicants => #error
entities.applicant_ids => #error

【问题讨论】:

    标签: ruby-on-rails activerecord associations searchkick


    【解决方案1】:

    像这样?

    Applicant.joins(:entity).where("entities.id < ?", 1000)
    

    【讨论】:

    • 谢谢,我不知道.joins。您的代码有效 - 但我简化了我的代码示例以使其可重现。在我的应用程序中,我使用的是 SearchKick,所以 entities = Entity.search params[:query] 查询可能很复杂。是否可以修改您的答案以使用entities 中的一组现有功能(而不是包括where 子句)?
    • 我不熟悉searchKick,我只玩过elasticsearch,看起来你需要预先加载关联,并定义你的search_data就像this一样,这让我有点困惑那,你想找到applicants给定entities,那么搜索应该在Applicant与关联的一边
    • 是的,你可能是对的,而不是搜索申请人。但是,实体具有我需要搜索的属性(在这种情况下是纬度/经度)。也许我需要重构模型和关系来支持这一点。不过,感谢您提供的提示。
    【解决方案2】:

    这个答案来自 SearchKick 的开发者 Andrew Kane:

    一种方法是使用include 选项来预先加载关联。

    Entity.search "*", include: [:applicants]
    

    另一种选择是从实体中获取所有 id,并将它们传递给 申请人查询。

    Applicant.where(entity_id: entities.map(&:id))
    

    我发现第二个选项对我很有效。

    【讨论】:

      【解决方案3】:
      Entity.where("id < ? ", 1000).includes(:applicants)
      

      获取所有申请者

      Entity.where("id < ? ", 1000).includes(:applicants).collect(&:applicants).flatten
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-11
        • 2018-11-20
        • 2023-01-30
        • 2017-08-29
        相关资源
        最近更新 更多