in Ruby on Rails

Integrating Search In a Rails App

After officially announcing version 0.1 of Dotawithme on the Dota subreddits we quickly realized we were going to need a search function in order to make the site useful (we had ~200 signups in 2 days). Thanks to yet another awesome Railscast I had an idea of where to start my quest.

I don’t want to spend time repeating what the Railscast episode will show you, but I generated a new model called search (searches) which will give us a URL structure of something like this http://dotawithme.com/searches/1. In this way each search will create a unique URL (/2, /3, etc etc). Originally we just toyed with making param calls in the url (ie: language=English&location=NorthAmerica) type and while this probably would have worked I decided to try out the Railscast way (although I am wondering how exactly this will scale as the site grows). Anyways, let’s get to the code!

In my new /models/search.rb I have the following:

These are just the different options you can search for. The one-five correspond to different positions that are played by teammates during the game. If you don’t know anything about Dota it’s ok; these are just booleans (and checkboxes on the screen).

In the controllers/searches_controller.rb I have the following:

It looks much like any other controller. The one interesting thing here is that in the def show we have both a @search and a @players being created. This is because we will be calling a partial from our /players/ to display our search.

In our /searches/show.html.erb we write:

This calls the partial /players/_player.html.erb which is simply a table displaying the data. It looks very similar to our /players/index.html.erb with the one difference being.. the partial does NOT use this statement.

Originally I had this in the partial as well (and was the reason I couldn’t push the search function live earlier). What would happen is for example 5 people were returned on the search. The table would be listed 5 times showing each of the results in each table (ie 25 listings). I realized that this is because the /searches/show.html.erb is calling the partial for every single listing. Perhaps there is a more efficient way of calling the data? If you know, please let me know.

I think I’m including everything that is needed to make search work (after you follow the Railscast episode). The Railscast episode did not work out of the box for me. The things I listed here are just what I needed to do to get it working correctly. So if Railscast episode 111 does not work for you maybe you can find your solution in the code I listed!

Write a Comment

Comment