Skip to content

Instantly share code, notes, and snippets.

@SeaOfLee
Last active November 3, 2016 01:23
Show Gist options
  • Select an option

  • Save SeaOfLee/913b249e178f167ac708 to your computer and use it in GitHub Desktop.

Select an option

Save SeaOfLee/913b249e178f167ac708 to your computer and use it in GitHub Desktop.
Add Searchkick to Rails 4 Project

##Add Searchkick to Rails 4 Project Shoutout to Ankane for creating the Searchkick gem. Also props to Mackenzie Child for his wonderful tutorial "How To Build a Movie Review App in Rails 4". At the end of the tutorial he covers how to install search into an app via the searchkick gem.

Download and install Java.

Install elasticsearch from the CLI:

$ brew install elasticsearch

If you already have elasticsearch installed, you can get more info:

$ brew info elasticsearch

This will give you ways to launch elasticsearch from the command line. This will need to be fired up like a server from port 9200 for the search/site to work properly.

To ensure searchkick is working properly, open a browser and navigate to:

localhost:9200

You should see some JSON data indicating the search function is working.

First we need to add searchkick to the model we want to search (in this example we're adding search to the User model). In User.rb:

class User < ActiveRecord::Base
  searchkick

Now let's reindex the User table. From CLI:

$ rake searchkick:reindex CLASS=User

We need to give searchkick some routes. Head over to config -> routes.rb and add:

resources :users do
    collection do
      get 'search'
    end
end

Add a search bar/form to a page (such as application.html.erb)...

<%= form_tag search_users_path, method: :get do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag("Search") %>
<% end %>

Define a search action in the controller (in this case users_controller.rb):

def search
    if params[:search].present?
      @users = User.search(params[:search])
    else
      @users = User.all
    end
  end

We need a place to display our beautiful search results...let's make a view for it. In this case we created search.html.erb in app -> views -> users. This is similar to an index view, I would recommend copying the code from there.

Fire up your rails server and check out the search function...hopefully it works! Check out the Mackenzie Child video referenced above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment