Rails Searchkick / Elasticsearch has_many 和 belongs_to 关联

Rails Searchkick / Elasticsearch has_many and belongs_to associations

我正在尝试使用 Searchkick 运行 搜索并 return 基于多个模型。

我的书模型包含这个

class Book < ActiveRecord::Base

  searchkick

  has_many :book_subjects
  has_many :subjects, through: :book_subjects

  belongs_to :author
  belongs_to :publisher

end

然后我的控制器有这个

def index

 if params[:search].present?
   @books = Book.search(params[:search], operator: "or")
 else
  @books = Book.all
 end
end

我希望搜索结果能够搜索关联的模型和 return 那里的任何结果 -- 所以 boo 主题名称、作者和出版商。

谢谢

在您的 Book 模型中,您需要有一个 search_data 块用于索引。

def search_data
  attributes.merge(
    author_name: author(&:name)
    publisher_name: publisher(&:name)
    subjects_name: subjects.map(&:name)
  )
end

这会将关联添加到您的索引中。

您对 has_many 个关联使用 .map 方法。