algoliasearch-rails gem connects your Rails models to Algolia.
It uses Rails callbacks to update your Algolia index when you create, update, or delete records.
It also adds a search method to your models.
The gem builds on the Algolia API client for Ruby.
Its source code is open source under the MIT license.
For a sample Rails app with Autocomplete and InstantSearch results pages, see the algoliasearch-rails-example repository.
Before you begin
You need:- An Algolia account
- Ruby 2.5 or later
- Ruby on Rails 6 or 7
Set up the gem
Set up the gem in a new Rails app. Then index and search a record.1
Create a Rails app
To create a new Rails app, run:
2
Install the gem
To add the gem to your
Gemfile and install it, run:3
Configure the gem
To configure the gem, create Replace
config/initializers/algoliasearch.rb in your Rails app.Ruby
ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY with your Algolia credentials.
Find both in the Algolia dashboard.
To run this test, use an API key with the search, addObject, and editSettings access control list (ACL) permissions.4
Create a model
To create a
Contact model and its database table, run:5
Connect the model to Algolia
To send your model to Algolia,
include the Replace
AlgoliaSearch module and the algoliasearch block.
This block sets up your and options.
An empty block sets up the default options.Replace the contents of app/models/contact.rb:app/models/contact.rb
INDEX_NAME with the name of a new test index.
The synchronous option makes each write wait for Algolia to finish indexing.
This lets you search right after you add a record.For a full configuration example, see the HN Search Item model.6
Index and search a record
To add a record and search for it, run:If the setup works, the command prints
Jon Doe.
Each run adds another record to your test index.
To remove the test data, delete the index in the Algolia dashboard or with the Algolia CLI.Use a custom API client
By default, the gem creates the Algolia API client from your configuration. To change client options, such as timeouts, create the client yourself. For the available options, see Customize the API clients. Inconfig/initializers/algoliasearch.rb, assign the client to AlgoliaSearch.client:
Ruby
Method names and aliases
TheAlgoliaSearch module adds the prefix algolia_ to every method it injects.
It also adds a short name for each method.
If Rails already defines the same name, the module skips the short name.
Ruby
Next steps
- Indexing: manage Algolia indices with your Rails models
- Index settings: customize index names and settings
- Search: build a search experience for your Rails app