Rails Searchkick / Elasticsearch has_many和belongs_to关联 [英] Rails Searchkick / Elasticsearch has_many and belongs_to associations
本文介绍了Rails Searchkick / Elasticsearch has_many和belongs_to关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Searchkick来运行搜索并基于多个模型返回。
Im trying to use Searchkick to run a search and return based on multiple models.
我的图书模型包含这个
class Book < ActiveRecord::Base
searchkick
has_many :book_subjects
has_many :subjects, through: :book_subjects
belongs_to :author
belongs_to :publisher
end
然后我的控制器有这个
and then my controller has this
def index
if params[:search].present?
@books = Book.search(params[:search], operator: "or")
else
@books = Book.all
end
end
我希望搜索结果搜索相关模型,并返回任何结果 - 所以boo主题名称,作者和发行人。
I want the search results to search the associated models and return any results there too -- so the boo subject name, the author and the publisher.
谢谢
推荐答案
在您的图书模型中,您需要有一个 search_data
块用于索引。
In your Book model you need to have a search_data
block for the indexing.
def search_data
attributes.merge(
author_name: author(&:name)
publisher_name: publisher(&:name)
subjects_name: subjects.map(&:name)
)
end
这将添加关联到您的索引。
this will add the associations to your index.
您可以使用 .map
方法为 has_many
协会。
You use the .map
method for the has_many
associations.
这篇关于Rails Searchkick / Elasticsearch has_many和belongs_to关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文