Creating a Search Bar in Rails
A few months ago, during the assessment of my Rails project at the Flatiron School the teacher asked me to implement a simple search feature in my project that would allow a user to search for all items within a particular search criteria.
What happened next was a mad dash of documentation searching to figure out how to implement such a feature in my project. I’m writing this in hopes of helping future Rails newbies who want to add search functionality into an application.
My search bar was designed so that a user could search for all properties within a particular location.
The first thing to consider is where in the application we want the search functionality to appear. For most applications, the index view will be the best place for your search bar to live. To create the search field, use a form_tag
and include the proper path and method
, communicating to your search form where to send the criteria for your controller to return.
What this form_tag
is saying is basically, send this information to the properties index
controller action in the params hash, nested in the :search
key. We end our search form with a submit_tag
to ensure this information is sent somewhere.
Now it’s time to set up the index
action in our PropertiesController.
Our index
action checks to see if the params
hash includes a :search
key. If so, we’ll filter the properties displayed on the page with a custom class method which takes as an argument the information found in the :search
key.
@properties = Property.search(params[:search])
This leads us to our next and final step, writing that custom class method in our Properties
model.
Our class Property
is setup with a belongs_to
relationship meaning that every property has a foreign_key
called location_id
. This self.search
class method takes in an argument (search)
which is the name of the location we want to filter our properties by. Our .find_by
method sets the location
variable equal to a found location. If that location exists we then set our @properties
to equal the properties that have a foreign_key
of location_id
matching the id of our location
variable.
Building a search bar in a Rails project may seem a bit daunting at first, but it’s quite simple and adds some awesome functionality to our application!