Search code examples
ruby-on-railsrubyelasticsearchhas-manysearchkick

Find users items through association using Elasticsearch with Searchkick on Rails?


I have to search books, users have books through authors need to be able to search only their books without showing other users books.

books model

has_many :authors
has_many :users, through: :authors

I tried to search as described here but it did not work.

@Books = Book.search "*", where: { user_id: current_user.id}

I believe that it did not work because books model does not have user_id


Solution

  • There are probably a few ways you could do this. Here's one: Search through the Books Index in searchkick, but only return the books whose id matches one of the users book_ids

    user model

    # assuming you have:
    has_many :books, through: :authors
    

    in the controller

    # change your where clause to filter based on book id
    @Books = Book.search "*", where: { id: current_user.book_ids}