During the development of my new project, I read a lot on the REST subject. In my opinion, it is a nice way of keeping your application clean and maintainable. But I stumbled upon a small problem when I had to implement a search for my resources.
In all the examples you find on the net, you will see how to create your basic CRUD actions in REST. So create, update and delete isn’t a problem at all. But when it came to implement a search system, you find nothing. Well, nothing is a big word, you do find posts, but all of them work diffrent.
The first thing I needed to do was to deside how I would handle the search. The first possibility is to create a new controller so it would fit in the REST filosophy. Just see the search as a resource. I didn’t realy feel right to see a search as a separate resource. I just see the search as a filter on an existing resource, so why defining the search as a resource of its own??
The next logical step was just adding a new action in my resource controller called search. But again, a new action just to search? Not a real good idea I think. Like I said before, a search is just a filter on your list, so I should be part of the index action.
So there we go. We just send our search parameters to the index action and filter our list there where it should happen.
If it was just as simple as that. You can’t just use a normal POST method form, becouse Rails will see that as create. And if I would use the GET method, all the search parameters would apear in the address bar. I know thats not a big of a deal, but I personaly think that isn’t realy clean.
But then it came to me. We live in an age where you can’t find an application without Ajax. So why not implement our search with Ajax? This way, we can send a GET request with our search parameters to the controller and rebuild our list without having to reload the whole page.
Some readers might think, building your search in the index action will make your index action look ugly. Well, for those readers, check out my previous post on building your query string dynamically in an object-oriented way with ActiveRecord.
As far as I know, this is the cleanest way to implement a search the RESTful way. But ofcourse, this is just my vision on the subject, and other developers will say you HAVE to create a separate controller. But if you think like me, and can’t comprehend why a search is a separate resource, my filosophy will be a nice way to follow.
If you have some input or improvements, please do share them 🙂