Framework integration / Rails / Getting started

Set up Algolia for Ruby on Rails

The algoliasearch-rails gem lets you integrate the Algolia Search API to your favorite object-relational mapping (ORM). It’s based on the algoliasearch-client-ruby gem.

Check the algoliasearch-rails-example repository on GitHub for a sample Rails app with Autocomplete and InstantSearch results pages.

Compatibility

This gem supports:

  • Ruby versions 2.4 to 3.0
  • Ruby on Rails versions 5, 6 and 7.

This gem is compatible with:

Install

Install the gem directly:

1
gem install algoliasearch-rails

Or add it to your Gemfile:

1
gem "algoliasearch-rails"

And run:

1
bundle install

Configuration

To configure the gem, create a new file config/initializers/algoliasearch.rb.

Add your Algolia credentials: the application ID and the API key. You can find both in the Algolia dashboard.

1
2
3
4
AlgoliaSearch.configuration = {
  application_id: 'YourApplicationID',
  api_key: 'YourWriteAPIKey'
}

Timeouts

You can configure timeouts with the following options:

1
2
3
4
5
6
7
8
9
AlgoliaSearch.configuration = {
  application_id: 'YourApplicationID',
  api_key: 'YourWriteAPIKey',
  connect_timeout: 2,
  receive_timeout: 30,
  send_timeout: 30,
  batch_timeout: 120,
  search_timeout: 5
}

The algoliasearch block

To index your model into Algolia, include the AlgoliaSearch module and the algoliasearch block. This block sets up your index and options. If you want to use the default options, declare an empty block.

1
2
3
4
5
6
7
class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch do
    # Use all default configuration
  end
end

Example configuration

To see a full configuration example, see the repository for the HN Search app.

Method name and aliases

All methods injected by the AlgoliaSearch module have the prefix algolia_ and are aliased to short names if they aren’t already defined by Rails:

1
2
3
4
5
6
7
# Both calls do the same
Contact.algolia_reindex!
Contact.reindex!

# Both calls to the same
Contact.algolia_search("jon doe")
Contact.search("jon doe")
Did you find this page helpful?