Rails Searchkick / Elasticsearch has_many and belongs_to associations

心已入冬 提交于 2019-12-04 14:29:15

问题


Im trying to use Searchkick to run a search and return based on multiple models.

My book model contains this

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

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.

thanks


回答1:


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.

You use the .map method for the has_many associations.



来源:https://stackoverflow.com/questions/31046428/rails-searchkick-elasticsearch-has-many-and-belongs-to-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!