Search through a has many relation with algolia-rails


As a newbie I’m having a rough time figuring this out. I have two ActiveRecord models: Contact which belongs to Account and account which has many contacts.

  class Contact < ActiveRecord::Base
    include AlgoliaSearch

    belongs_to :account

    algoliasearch do
      attribute :account_id, :full_name, :email, :tax_id, :contact_name

      searchableAttributes ['full_name', 'email', 'tax_id', 'contact_name']

      customRanking ['asc(full_name)']

  class Account < ActiveRecord::Base
    has_many :contacts

What I’m trying to do is to get an already scoped list of contact IDs from the algolia search so I won’t hit another account contact IDs (which would mess with the hits per page with pagination). The following query for example:


should only use the IDs from contacts where the account_id is the same than I think it has something to do with facets but I’m not pretty sure.


Hi @john1, thanks for asking your question.

Yes, you will want to add a filter at query time that restricts the search to a particular contact ID. Check out the Search Parameters section of the JavaScript API client docs and the corresponding filtering docs to see how you can do that.

Many thanks :+1: for pointing me into the right direction. I’ve ended filtering with facets like this:

current_account.contacts.algolia_search(‘Tom’, facets: ‘account_id’, facetFilters: “account_id:#{}”)

1 Like