0
votes

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.

  • Search users which have no book associated.
  • Search users with at least one book associated.
  • Search users with at least book of a specific type, say 'Arts'.

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.

1

1 Answers

0
votes

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"})