Only index objects that meet a certain condition

I’m playing around with the algolia rails gem, and can’t seem to find a solution to this. I want to index Post objects, but only posts that meet a specific condition, specifically those that have live status codes (Post.where(status_code: [1,2,3]) or posts where live? returns true).

Adding a conditional into the algoliasearch block doesn’t actually seem to work.

Any ideas?

1 Like

Hi Jean,

You are definitely on the right track: in order to conditionally index records you need to use something like this:

class Post < ApplicationRecord
  include AlgoliaSearch

  algoliasearch if: :indexable? do
  end

  def indexable?
    return true if self.live? || [1, 2, 3].include?(self.status)

    false
  end
end

Also remember to reindex your Post model by using Post.reindex! on rails console.

Let me know if this works out for you!

3 Likes

Hi Gianluca,

That was exactly what I needed.

Thank you!

1 Like