Simple Search Form in Rails

Simple Search Form in Rails

This is a quick tutorial on how to generate a simple search form to filter out what is displayed on a Rails Web Application view page.

Image for post

MVC structure

Two models: Superhero and Superpowers. A superhero can only have one superpower. A superpower can have many superheroes.

The superheroes/index.html.erb view file displays all of the superheroes in the database, and sets up a simple search form to filter the superheroes by superpower.

Image for postsuperheroes/index.html.erb

This code will bring up the search bar on the view page. Note that I set the route superheroes_path and mehod: :get. Below are the routes for my program. When submitting the search, the form will load the superheroes_path url and submit a GET request. This is because we want to filter the results on our index page, not post anything to our database. After clicking submit, the program will reload the index view page, but this time with a :search param. More about that below.

Image for postrails routes

If you typed a superpower in the search bar and then clicked submit, an error would come up. this is because there is no :search key permitted in your params yet (the :search key was defined in your form above) You need to make sure to permit the term field :search in the superhero_params method in the superhero controller. The :search key in your params will now have the value of whatever you type in the search bar.

Image for postSuperhero params

Now, the index action in the superhero controller defines @superheroes as the return of calling a class method search on the Superhero class, and taking in params[:search] as an argument. Remember, if the index page is loaded without a search input, params[:search] will equal nil.

Image for postSuperhero controller

The Superhero class has a class method called search and takes in one argument. Remember, if the index page is loaded without a search input, that argument will be nil.

Image for postSuperhero model

Here we have an if/else statement. If the argument search is true (not nil), then a block is run where the superpower object is found based on params[:search]. Then, the superheroes with the found superpower are all returned using the where method.

If params[:search] is nil, then the method will return a list of all superheroes. So, if the index view is loaded without a trueparams[:search], then all the superhero instances will be listed. If the index view is loaded with a trueparams[:search], then the program will only list which superheroes match the given search.

It?s also possible for a user to input an invalid superpower string. This would mean that the program would not be able to find an existing superpower in line 17. So, in line 18, we check to make sure the superpower object is found.If not, display Superhero.all. I know it?s bulky, but it works.

Image for post

11

No Responses

Write a response