Rails - 从集合中获取多态的子级为ActiveRecord :: Relation

时间:2018-05-02 01:34:48

标签: ruby-on-rails activerecord children polymorphic-associations pg-search

我需要让父母的所有孩子都成为ActiveRecord :: Relation。事实是,这些孩子存储在多态关系中。在我的情况下,我需要它来为使用pg_search gem获得的一些搜索结果分页。

我尝试了以下内容:

results = PgSearch.multisearch('query').map(&:searchable)
# Horrible solution, N + 1 and returns an array

docs = PgSearch.multisearch('query').includes(:searchable)
results = docs.map(&:searchable)
# Still getting an array

还考虑过select或pluck之类的东西,但它们不是用于检索对象,而是用于检索列数据。我可以尝试搜索每个子类型的ID,如此

Post.where(id: PgSearch.multisearch('query').where(searchable_type: "Post").select(:searchable_id)
Profile.where(id: PgSearch.multisearch('query').where(searchable_type: "Profile").select(:searchable_id)

但它没有扩展,因为我需要为我想从搜索结果中获取的每个对象执行此操作。

任何帮助都将不胜感激。

修改 这里有一些基本的伪代码来证明这个问题:     class Profile< ApplicationRecord       has_one:search_document,:as => :搜索     端

class Post < ApplicationRecord
  has_one :search_document, :as => :searchable
end

class Profile < ApplicationRecord
  has_one :search_document, :as => :searchable
end

class SearchDocument < ApplicationRecord
  belongs_to :searchable, plymorphic: true
end

我想获取所有可搜索的项目作为ActiveRecord :: Relation,以便我可以使用limit(x).offset(y)

在这种特定情况下动态过滤它们
SearchDocument.all.joins(:searchable).limit(10).offset(10)

生成错误:无法急切加载可搜索的多态关系原因

SearchDocument.all.includes(:searchable).limit(10).offset(10)

这个确实会将可搜索的项目加载到内存中,但不会在查询中返回它们,而是按预期将过滤器应用于SearchDocument项目。这可能是一个临时解决方案,用于过滤搜索文档,然后从中获取可搜索的项目,但会与视图中的分页发生冲突。

这里的问题是:有没有办法可以将所有可搜索的项目作为ActiveRecord :: Relation来进一步过滤它们?

1 个答案:

答案 0 :(得分:0)

我对这个图书馆不太熟悉。但是,看看你的代码,我猜想任何尝试使用CollectionProxy并在其上映射一些函数都会触发评估CollectionProxy并返回一个数组。

快速浏览一下库GitHub文档,也许这样的事情可能有用:

post_docs = PgSearch.multisearch('query').where(searchable_type: "Post")
posts = Post.where(pg_search_document: post_docs)
相关问题