正在搜索 has_many 与 Searchkick 的关联

Searching has_many association with Searchkick

我正在尝试为我的应用构建搜索功能,并且 运行 遇到了一些关于能够搜索 has_many 关联的问题。我希望对其进行设置,以便用户只能看到他们有权访问的项目。

在我的用户模型中,我有:

class User < ApplicationRecord
    searchkick
    has_many :items, -> (user) { unscope(:where).where("(consumer_type = ? and consumer_id = ?))", 'User', user.id) }, fully_load: false, dependent: :destroy

    # not sure if this is helpful, was messing around with this
    def search_data
        {
            name: items.name
        }
    end
end

然后在我的项目模型中我有:

class Item < ApplicationRecord
    belongs_to :consumable, polymorphic: true
    belongs_to :consumer, polymorphic: true
end

然后我还有两个模型,"Book"和"Camera"属于Item。我需要能够在我的控制器中 运行 查询,例如:

@results = current_user.items.search('Query')

... 这样 returns 与搜索查询相匹配的图书和相机结果。 我阅读了 Searchkick 文档的 Personalized Results 部分,但根本无法让它工作。 任何有用的提示,或者是否有人对特定用户取得了类似的范围界定结果?

@results = current_user.items.search('Query')

这样搜索是不可能的。如果是,那么它将影响从两个数据源查询并获得结果集的交集的性能。所以从项目末尾开始,将用户信息包含到该模型中。

class Item
 searchkick word_middle: %i[name]
 def search_data
   {
     consumer_type: consumer.class.to_s
     consumer_id: consumer.id.to_s
     name: self.name
   }
 end
end

options = {where: [{consumer_type: 'User', consumer_id: current_user.id.to_s}]}
results = Item.search 'query', options