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.
Compatibility
This gem supports:
- Ruby versions 2.5 and up
- Ruby on Rails versions 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'}
API client with custom settings
If you want to customize settings such as timeout for the API client, you can make the Algolia gem use your instance of an API client. You can do this by setting the AlgoliaSearch.client
option to your initialized client:
1 2
opts={}# your optionsAlgoliaSearch.client=Algolia::SearchClient.create('YourApplicationID','YourWriteAPIKey',opts)
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
classContact<ActiveRecord::BaseincludeAlgoliaSearchalgoliasearchdo# Use all default configurationendend
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 sameContact.algolia_reindex!Contact.reindex!# Both calls to the sameContact.algolia_search("jon doe")Contact.search("jon doe")