Meilisearch v1.15 is here ✨ Read more

Go to homeMeilisearch's logo
Back to articles
17 Jun 2025

Full tutorial on how to design a search engine with Ruby on Rails

Learn how to easily build a search engine with Ruby on Rails in this actionable step-by-step tutorial.

Ilia Markov
Ilia MarkovSenior Growth Marketing Managernochainmarkov
Full tutorial on how to design a search engine with Ruby on Rails

Imagine you're building a blog in Rails, and your users keep misspelling post titles in the search bar, only to find no results. Frustrating, right?

What if your Rails app or website had a search feature that’s lightning-fast *and *smart enough to handle typos?

Meilisearch is your answer. It's a lightweight, typo-tolerant, and lightning-fast search engine that offers a seamless developer experience and out-of-the-box relevancy tuning.

You can make a search engine with Ruby on Rails in Meilisearch by:

  1. Setting up Meilisearch and installing dependencies.
  2. Configuring Meilisearch in the Rails app.
  3. Defining a model and enabling Meilisearch indexing.
  4. Populating and indexing data.
  5. Implementing a backend and frontend.
  6. Customizing settings.

A Ruby on Rails–powered search engine can be used for building e-commerce platforms, blogs, or searchable knowledge bases. Regardless of your use case, a search engine built with Ruby on Rails in Meilisearch comes with a slick search interface that’s both powerful and user-friendly.

1. Set up Meilisearch and install dependencies

First, we need to get Meilisearch up and running and integrate it with our Rails app. This will lay the foundation for your search engine.

Meilisearch is open source and free if you choose to host it locally. Or, you can choose Meilisearch Cloud for a fully managed hosting experience, with no need to handle infrastructure or updates yourself.

For this tutorial, we’ll use a local instance, which is perfect for testing. You’ll need Ruby 3.0+ and Rails 6.1+ to ensure compatibility. Older versions may still allow it to function, but they are not officially supported.

The meilisearch-rails gem simplifies the integration, handling indexing and syncing with your database. Let’s install Meilisearch and add the gem to your project.

To install Meilisearch locally, follow the instructions in the official Meilisearch documentation on GitHub. You can download the binary and run it with a simple command. Once running, Meilisearch is accessible at http://127.0.0.1:3000.

Open your Gemfile and, with gem in the command line, add:

gem install meilisearch-rails

source 'https://rubygems.org'

gem 'meilisearch-rails'

Run bundle install to install the gem. If you hit any issues, double-check your Ruby and Rails versions, as the gem requires recent versions for full compatibility.

With Meilisearch and the gem installed, we’re ready to configure our Rails app to connect to it.

2. Configure Meilisearch in your Rails app

Now, let’s configure our Rails app to connect to Meilisearch. Think of this step as setting the coordinates that guide your app to the search engine.

Create a new configuration file to specify the MEILISEARCH_HOST and MEILISEARCH_API_KEY. This ensures smooth and secure communication between your app and Meilisearch.

In development, you can skip the API key, but in production, it’s essential for maximum security. Proper configuration, such as what we’re doing now, prevents connection errors and ensures smooth indexing and searching.

Create a new file at config/initializers/meilisearch.rb:

Meilisearch::Rails.configuration = {
  meilisearch_url: ENV.fetch('MEILISEARCH_HOST', 'http://localhost:7700'),
  meilisearch_api_key: ENV.fetch('MEILISEARCH_API_KEY', 'YourMeilisearchAPIKey')
}

If you’re using Meilisearch Cloud, replace the URL with your cloud instance’s address, which is available after signing up for Meilisearch Cloud. For local development, the default URL works fine. If you encounter connection issues, ensure Meilisearch is running and the URL is correct.

Now that our app knows where to find Meilisearch, let’s set up a model to index data.

3. Define a model and enable Meilisearch indexing

This step is where the magic starts: we’ll make our data searchable by indexing it with Meilisearch. Indexing means cataloging your information and data so Meilisearch can quickly find matches during user searches.

For this example, we’ll use the hypothetical Rails model Article and include the MeiliSearch::Rails module to enable automatic indexing. You’ll decide which attributes to index, like title and body, and configure how they’re used in searches. Meilisearch syncs with your database via ActiveRecord callbacks, so you don’t have to worry about updating it manually.

First, generate a model if you don’t have one:

rails generate model Article title:string body:text category:string
rails db:migrate

Then, open app/models/article.rb and add:

class Article < ApplicationRecord
  include MeiliSearch::Rails

  meilisearch do
    attribute :title, :body, :category
    searchable_attributes [:title, :body]
    filterable_attributes [:category]
    sortable_attributes [:created_at]
  end
end

Here’s what’s happening:

  • attribute lists the fields requiring indexing.
  • searchable_attributes are fields users can search.
  • filterable_attributes allow filtering of the results, e.g., by category.
  • sortable_attributes enable sorting, e.g., by creation date.

Here, choosing the right attributes is crucial. For example, indexing title and body makes sense for a blog, but you might want to add tags or author depending on your use case. Choose only the most relevant fields to index for better performance and faster search results.

With our model ready, let’s add some data to the index.

4. Populate and index sample data

To test our search engine, we need data to search through. For this purpose, we will populate our database with sample articles.

Using a seed file, we’ll create sample records that Meilisearch will automatically index. This will let you see how Meilisearch handles real data and prepare you for testing search queries. Meilisearch’s efficiency really shines here, as it can index thousands of records at lightning speeds.

To start, create or update db/seeds.rb with the articles you want searched:

# Clear existing articles — use only in development or testing!
Article.destroy_all
articles = [
  { title: "Ruby on Rails Basics", body: "Learn the fundamentals of Rails.", category: "Beginner" },
  { title: "Advanced Rails Techniques", body: "Dive into complex Rails features.", category: "Advanced" },
  { title: "Rails Performance Tips", body: "Optimize your Rails app.", category: "Performance" },
  { title: "Building APIs with Rails", body: "Create robust APIs in Rails.", category: "API" },
  { title: "Rails Security Best Practices", body: "Secure your Rails application.", category: "Security" }
]
articles.each { |article| Article.create!(article) }
puts "Articles seeded!"

Then, run:

rails db:seed

Meilisearch will index these records automatically using the aforementioned ActiveRecord callbacks. To verify, you can use Meilisearch’s API or dashboard to check the articles index. If (correct) data isn’t appearing, ensure your Meilisearch instance is running and the configuration is correct.

Now, things get even more interesting — it’s time to implement the search functionality.

Ready to try it out? See Meilisearch’s search capability in full force in a free trial!

5. Implement backend search functionality

First, we’ll create a controller to handle search queries and display accurate results.

This step sets up a SearchController to process user input and fetch results from Meilisearch. The meilisearch-rails gem makes this easy by providing a search method that returns ActiveRecord objects, so you can treat results like regular model instances. Additionally, Meilisearch’s typo tolerance ensures users get relevant results even with misspellings.

Create app/controllers/search_controller.rb:

class SearchController < ApplicationController
  def index
    @query = params[:q]
    @results = Article.search(@query) if @query.present?
  end
end

Update your routes in config/routes.rb:

Rails.application.routes.draw do
  get 'search', to: 'search#index'
end

Create a view at app/views/search/index.html.erb:

<h1>Search Articles</h1>
<%= form_with url: search_path, method: :get, local: true do %>
  <%= text_field_tag :q, params[:q], placeholder: "Search articles..." %>
  <%= submit_tag "Search" %>
<% end %>

<% if @results %>
  <h2>Results for "<%= @query %>"</h2>
  <ul>
    <% @results.each do |result| %>
      <li><strong><%= result.title %></strong>: <%= result.body %></li>
    <% end %>
  </ul>
<% end %>

Visit http://localhost:3000/search and try queries like ‘Ralis’ (a typo for ‘Rails’). Meilisearch’s typo tolerance will still return relevant results, as expected. If results aren’t appearing at all, or they seem to be incorrect, check your model’s indexing settings or Meilisearch logs.

Now, let’s take it up a notch with a frontend search interface through our JavaScript API Client or Instant Meilisearch plugin.

6. Add a frontend search with instant Meilisearch

For a search-as-you-type experience, we’ll integrate Meilisearch’s simple frontend interface using instant-meilisearch.

This step enables dynamic, instant search functionality in your app, giving users an interactive experience as they type. Meilisearch’s impressive response speed — with response times ≤50ms — ensures results appear almost instantly. We’ll use a simple JavaScript setup, but you can extend it with frameworks like React for a polished UI.

Install the library via npm (or yarn). Note: this assumes your Rails app is already set up with a JavaScript bundler such as Webpacker or Importmaps.

npm install @meilisearch/instant-meilisearch

Create app/javascript/search.js:

import { instantMeiliSearch } from '@meilisearch/instant-meilisearch';

const searchClient = instantMeiliSearch(
  '',// URL of Meilisearch instance
  '' // Meilisearch API key
);

const search = async (query) => {
  const response = await searchClient.search([{
    indexName: 'articles',
    query
  }]);
  const resultsDiv = document.getElementById('results');
  resultsDiv.innerHTML = response.hits.map(hit => `<div>${hit.title}: ${hit.body}</div>`).join('');
};

document.getElementById('search-input').addEventListener('input', (e) => {
  search(e.target.value);
});

Update app/views/search/index.html.erb:

<h1>Search Articles</h1>
<input type="text" id="search-input" placeholder="Search articles...">
<div id="results"></div>

As before, test the search at http://localhost:3000/search. Typing ‘Rail’ should show results instantly.

Next, let’s explore our customization options.

7. Customize Meilisearch settings

To make your search engine even better, you can tweak Meilisearch’s settings to fit your product’s needs.

Meilisearch allows you to customize ranking rules, synonyms, and stop words to improve search relevance. For example, you might want ‘Rails’ and ‘Ruby on Rails’ to be treated as synonyms, or prioritize results based on recency.

For instance, here is how to adjust ranking rules to prioritize certain fields:

Article.meilisearch_index.update_settings({
  rankingRules: [
    "words",
    "typo",
    "proximity",
    "attribute",
    "sort",
    "exactness",
    "created_at:desc"
  ]
})

These settings ensure newer articles rank higher. Feel free to play around and test different configurations to see what works best for your users.

Finally, let’s ensure your search index stays in sync with your database for the most accurate results.

8. Handle updates and deletions

The meilisearch-rails gem automatically handles indexing when you create or update records. However, it’s still worth understanding how to manage updates and deletions yourself, especially if you’re building more complex web applications. This will ensure your search results always reflect the latest data and avoid stale or missing entries.

To manually delete a record from your index:

article = Article.find(1)
article.remove_from_index!
Article.destroy! # Removes from Meilisearch index

If you need to reindex all records, for example, after changing any indexed attributes, run:

Article.reindex!

To clear your index entirely, use:

Article.clear_index!

Be cautious with reindexing large datasets, however, as it can be resource-intensive. In production environments, you can schedule such tasks during low-traffic periods.

Can I make a search engine with Ruby on Rails for free?

Yes, you can build a search engine with Ruby on Rails and Meilisearch at no cost for development and small-scale production.

Meilisearch’s open-source version is free to self-host on your own servers or local machine, and the meilisearch-rails gem has no licensing fees. For development, this is ideal, as you only need a server to run Meilisearch.

For production, however, hosting costs depend on your infrastructure. Small apps can run on affordable servers, while the costs may skyrocket for larger projects.

Meilisearch Cloud offers a 14-day free trial without requiring a credit card, making it perfect for testing. Post-trial, pricing scales with usage (documents and search requests), starting with the Build plan for small businesses at $30/month.

Let’s compare Meilisearch to other open-source search engines.

What are the best open-source search engines for Ruby on Rails?

Open-source search engines provide powerful, license-free solutions for adding search to Rails apps. Here are the top options:

  • Meilisearch: Known for its speed (under 50ms) and simplicity, Meilisearch integrates seamlessly with Rails via the meilisearch-rails gem. It’s ideal for small to medium apps, offering typo-tolerance and search-as-you-type features. Its lightweight nature makes it easy to set up and maintain yourself, while also providing a hosted option for a maintenance-free experience.
  • Elasticsearch: A robust engine, Elasticsearch excels in handling large datasets and complex queries. Gems like Searchkick simplify integration. It’s perfect for enterprise apps but requires more resources and setup than Meilisearch.
  • Solr: Solr offers advanced functionalities like full-text search and faceting. The Sunspot gem provides Rails integration. It’s highly configurable, which can get complex for smaller projects.
  • Typesense: A lightweight alternative for creating search engines for Ruby on Rails, Typesense offers fast, typo-tolerant search. While it lacks a dedicated Rails gem, its API is easy to use for simple setups.

Now, let’s look at other languages for building search engines.

What programming languages besides Ruby are used to build search engines?

Aside from Ruby, several programming languages are well-suited for building search engines, each with its unique strengths. Some common languages you can use to build search engines are:

  • JavaScript: Using Node.js, you can build server-side search with libraries like Lunr or integrations with Meilisearch. JavaScript’s asynchronous nature is great for real-time search. Learn how to build a search engine in JavaScript.
  • PHP:Frameworks like Laravel use Scout to integrate with Meilisearch, making PHP a solid choice for web apps that include search engines. Learn how to build a search engine in PHP.
  • Golang: Golang’s performance and concurrency make it ideal for high-speed search engines. Libraries like Bleve support full-text search, further increasing its applicability. Learn how to build a search engine with Golang.

Creating a search engine in Ruby on Rails made simple

Building a search engine with Ruby on Rails and Meilisearch is easier than you’d think. Set up Meilisearch, index data, add a backend and frontend, and customize the settings to your heart’s content. Meilisearch’s speed, typo-tolerance, and seamless Rails integration make it a top choice for developers looking for fast search engine configuration.

With Meilisearch, you can create a fast and scalable search engine

Meilisearch’s sub-50ms response times and user-friendly features ensure a great experience for both you and your users, whether you’re building a blog, e-commerce site, or internal tool. Plus, you can start for free and scale as needed.

Building a search engine in Golang: A comprehensive guide

Building a search engine in Golang: A comprehensive guide

Learn how to easily build a search engine in Go (Golang) in this actionable step-by-step tutorial.

Ilia Markov
Ilia Markov12 Jun 2025
How to add search to your Gatsby site: Step-by-step guide

How to add search to your Gatsby site: Step-by-step guide

Learn how to easily add search to your Gatsby site with this detailed and easy-to-follow step-by-step guide.

Ilia Markov
Ilia Markov11 Jun 2025
How to build a search engine in PHP: Step-by-step guide

How to build a search engine in PHP: Step-by-step guide

Learn how to easily build a search engine in PHP in this actionable step-by-step tutorial.

Ilia Markov
Ilia Markov05 Jun 2025