使用Searchkick搜索has_many关联 [英] Searching has_many association with Searchkick

查看:50
本文介绍了使用Searchkick搜索has_many关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序构建搜索功能,并且在能够搜索has_many关联方面遇到了一些问题.我希望进行设置,以便用户仅看到他们有权访问的项目.

I'm attempting to build out a search feature for my app and am running into some issues with being able to search a has_many association. I want it set up so that a user only sees items that they have access to.

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

In my user model, I have:

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

然后在我的商品模型中,我拥有:

Then in my Item model I have:

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

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

Then I have two more models, "Book" and "Camera" that belong to Item. I need to be able to run a query in my controller such as:

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

...,以便它返回与搜索查询匹配的Book和Camera结果.我阅读了Searchkick文档的个性化结果部分,但无法使其正常运行全部.有任何有用的提示,还是有人实现了与特定用户类似的范围界定结果?

... so that it returns both Book and Camera results that match the search query. I read the Personalized Results section of the Searchkick docs, but was unable to get it to work at all. Any helpful tips, or has anybody achieved something similar scoping results to a specific user?

推荐答案

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

不可能这样搜索.如果是的话,从两个数据源中查询结果并与结果集相交会影响性能.因此,请从项目末尾开始,并在该模型中包含用户信息.

It's not possible to search like this. and if it was then it'll hit the performance to query from both data sources and get intersect of the results set. so start from the item end and include user info to that model.

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

这篇关于使用Searchkick搜索has_many关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆