【发布时间】:2023-03-06 08:18:01
【问题描述】:
Searchkick - 具有多个模型和字段的自动完成
我正在努力为与我的Post 模型关联的多个模型实现autocomplete functionality。搜索功能工作正常并返回预期数据。如果我按照documentation 中的方式实现它,我的自动完成方法也可以正常工作(但仅适用于帖子的标题)。
我还尝试通过将Post.index.name 切换为Post.searchkick_index.name 来尝试this answer 和这个one,但不显示自动完成功能。
这是我在posts_controller.rb写的代码:
def autocomplete
render json: Post.search(params[:query],
index_name: [
Post.searchkick_index.name,
Tag.searchkick_index.name,
User.searchkick_index.name
],
limit: 10,
load: false,
misspellings: { below: 5 })
end
我也试过了:
def autocomplete
render json: Searchkick.search(params[:query],
models: [Post, Tag, User],
limit: 10,
load: false,
misspellings: { below: 5 })
end
上面的代码没有错误,但自动完成功能也不起作用。
在post.rb:
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many :posts_tags, dependent: :destroy
has_many :tags, through: :posts_tags
searchkick word_start: %i[title]
def search_data
{
title: title,
description: description,
user: user.full_name
}.merge(
tag: tags.map(&:title),
comments: comments.map(&:description)
)
end
end
按照答案部分的建议,我还尝试了以下方法:
def autocomplete
posts = Post.search(params[:query], execute: false)
tags = Tag.search(params[:query], execute: false)
users = User.search(params[:query], execute: false)
render json: Searchkick.multi_search([posts, tags, users])
end
这将返回以下错误:fatal - exception reentered。
我希望能够自动完成帖子的 title、标签的 title 和用户的 full_name。我应该如何更改我的代码?
提前谢谢你!
【问题讨论】:
标签: ruby-on-rails elasticsearch autocomplete typeahead.js searchkick