I was recently helping a friend out with his Rails project and we were trying to figure out the best way to handle queries in a RESTful Rails app, i.e. returning a subset of items meeting certain conditions. After a bit of poking around, here’s what looks like the most promising convention to follow (please post a comment if you disagree with the conclusion described here).
We had two inter-related questions:
- What should a query URI look like in a RESTful environment?
- What Rails coding pattern should be used to respond the RESTful query?
What should a query URI look like in a RESTful environment?
The main choices here seemed to be between including the query parameters in the path or placing them after a question mark, e.g.
/items/large or /items?size=large
The answer is: use the latter form: /items?size=large
[Note: the exception would be if you have a resource called LargeItem in your app. In that case you're really just looking at a standard REST collection GET which should be handled by the index method of your LargeItem controller.]
What Rails coding pattern should be used to respond the RESTful query?
So you’ve now opted for the URIs of the form /items?size=large. What code do you need to respond to these queries?
If you’re using the default Rails 2.0 RESTful resource scheme, queries will now be routed to the index method of your Item controller and your query parameters will be accessible via params, e.g. params[:size].
Your index method needs to return different subsets of your items collection depending on which (if any) query parameters have been passed in. For now I’ll probably put the logic to sort between the different cases in the controller, but it might be better to move it into the model (following the skinny controller, fat model pattern). Any thoughts on this?
How to link to specific queries
You can link to specific queries using something like this:
items_path(:size => ‘large’)
Many thanks to the following sources: