4

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 Answer 1

18

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.

4
  • Thanks, this was a good point in the right direction. the subject_name didn't work, but figured it out.
    – railsey
    Jun 30, 2015 at 16:58
  • does this update search_data when for example subject was edited? Feb 25, 2016 at 2:39
  • there is a little error with subject_name. Correct way to do this with a has_many association: subject_name: subjects.map(&:name) Mar 31, 2016 at 22:04
  • @railsey What worked for you re: subject_name? Because neither of the suggestions here work for me. Nov 4, 2016 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.