(Note: for Rails 7 or above projects, please reference rails-simple-search demo at here: github.com/yzhanginwa/rails_simple_search_demo)
This is a rails application. Its purpose is to demo the simplicity and power of gem rails-simple-search.
You can download it and run “bundle; rake db:migrate; rails s” immediately. It’s tested under Ruby 2.3.1 and Rails 4.2.6.
In this demo, I tried to search for a user by part of her name, her post titles, her comments, her address, her city, her state and so on.
The following is the code related to the search:
-
In file “Gemfile”
... gem 'rails-simple-search' # to use 1.1.1 or above ...
-
In file “app/model”Search“
class Search < RailsSimpleSearch::Base end
-
In file “config/route.rb”
... match '/users/index', :controller => 'users', :action => "index" ...
-
In file “app/controllers/users_controllers”
... @search = Search.new(:user, params[:search], exact_match: :first_name) @users = @search.run.paginate(page: params[:page], per_page: 20).order(:first_name) ...
-
In file “app/views/users/index.html.erb”
... <%= form_for @search, :url => "/users/index" do |f| %> <%= f.label "First Name" %> <%= f.text_field 'first_name' %> <br/> <%= f.label "Last Name" %> <%= f.text_field 'last_name' %> <br/> <%= f.label "Address1" %> <%= f.text_field 'address.address1' %> <br/> <%= f.label "City" %> <%= f.text_field 'address.city' %> <br/> <%= f.label "Post title" %> <%= f.text_field 'posts.title' %> <br/> <%= f.label "Post body" %> <%= f.text_field 'posts.body' %> <br/> <%= f.label "Comment" %> <%= f.text_field 'comments.body' %> <br/> <%= f.submit "search" %> <% end %> ...
For more info about rails-simple-search, please see “github.com/yzhanginwa/rails-simple-search”.