Hamza Iftikhar
Hamza Iftikhar

Reputation: 1

Searchkick search on model having no or at least one associated object

In Rails, I am using searchkick gem. There are two models user and book, I applied searchkick on user model. Both the models are given below:

class User < ApplicationRecord
  searchkick

  has_many :books
end

class Book < ApplicationRecord
  belongs_to :user
end

Book model has a type field. Now, I want to do different kind of queries on User model.

I have tried a number of queries and also tried join but of no use. If anyone can please help with queries to search such results.

I do not want to search in book model along with user model, just only in user model but having associated books.

Upvotes: 0

Views: 1443

Answers (1)

Andrew Kane
Andrew Kane

Reputation: 3236

Use a custom search_data method to add book info for your search index.

class User
  searchkick

  scope :search_import, -> { includes(:books) }

  def search_data
    {
      books_count: books.count,
      book_types: books.map(&:book_type)
    }
  end
end

class Book
  after_commit :reindex_user

  def reindex_user
    user.reindex # or reindex_async
  end
end

and search with:

User.search("*", where: {books_count: 0})
User.search("*", where: {books_count: {gt: 0}})
User.search("*", where: {book_types: "Art"}) 

Upvotes: 0

Related Questions