【发布时间】:2018-05-02 01:34:48
【问题描述】:
我需要从父级获取所有子级作为 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)
但它不能扩展,因为我需要为我想从搜索结果中获取的每个对象都这样做。
任何帮助将不胜感激。
编辑 这是一些演示该问题的基本伪代码: 类配置文件 :searchable 结束
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 来进一步过滤它们?
【问题讨论】:
标签: ruby-on-rails activerecord children polymorphic-associations pg-search