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

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


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

Let me know if this works out for you!


Hi Gianluca,

That was exactly what I needed.

Thank you!

1 Like