Implement Simple Search to Rails

This article assumes you have a Rails application with the models, views, and controllers all up running and you want to implement a simple search to your application. I have an app with a ‘note’ model and I would like to to implement simple search to make it easy for me to find specific notes using simple search key words in my rails application. Below I have a note model file, notes controller file and the notes index file.

  • Note Model File: This can be any other model file that you want to implement search on. Add the code below to your model file, I have mine as note.rb.
1
2
3
4
5
6
7
8
9
class Note < ApplicationRecord

.
.
.
def self.search(search)
where("title LIKE ? OR body LIKE ?", "%#{search}%", "%#{search}%")
end
end
  • Notes Controller File: Add this to the index action of your controller file, I’ve named mine notes_controller.rb.
1
2
3
def index
@notes = current_user.notes.recent.paginate(page: params[:page], :per_page => 25).search(params[:search])
end
  • Notes Index Page: Finally add the code below to your index file, my index page is in views/notes/index.html.erb file.
1
2
3
4
5
6
7
8
9
<div class="notes-container">
<div class="form-group">
<h3>My Notes</h3>
<%= form_tag(notes_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search],class: "form-control", placeholder: "Search Notes" %>
<%= submit_tag "Search Notes", title: :nil, class: "btn btn-info search-button" %>
<% end %>
</div>
</div>
  • That’s all you need to implement a simple search to your Ruby on Rails application, note I’m using Bootstrap for my front end, you don’t have to, but you can if you want.

If you have any questions or comments, please leave them below.