I started a Rails project recently and decided to use RESTful controllers. I created controllers for my key entities (such as Country) and added index
, new
, edit
, create
, show
, update
and delete
. I added my map.resources :country
to my routes file and life was good.
After development progressed a little, I started to encounter problems. I sometimes needed extra actions in my controller. First there was the search
action that returned the options for my fancy autocompleting search box. Then came the need to display the countries in two different ways in different places in the application (the data displayed was different too, so it wasn't just two views) - I added the index_full
action. Then I wanted to show a country by name in the URL, not by id so I added the show_by_name
action.
What do you do when you need actions beyond the standard index
, new
, edit
, create
, show
, update
, delete
in a RESTful controller in Rails? Do I need to add (and maintain) manual routes in the routes.rb file (which is a pain), do they go in a different controller, do I become unRESTful or am I missing something fundamental?
I guess I am asking, do I need to work harder and add actions into my routes.rb file for the privilege of being RESTful? If I wasn't using map.resources
to add the REST goodies, the standard :controller/:action, :controller/:action/:id
routes would handle pretty much everything automatically.
I would treat search
as a special case of index
. Both actions return a collection of resources. The request parameters should specify things like page, limit, sort order, and search query.
For example:
/resources/index # normal index /resources/index?query=foo # search for 'foo'
And in resources_controller:
before_filter :do_some_preprocessing_on_parameters def index @resources = Resource.find_by_param(@preprocessed_params) end
As for index_full
and search_by_name
, you might look at splitting your current controller into two. There's a smell about what you've described.
Having said that, you're absolutely right that there's no point in forcing your app to user restful routes when it doesn't deliver anything over /:controller/:action/:id
. To make the decision, look how frequently you're using the restful resource route helpers in forms and links. If you're not using them, I wouldn't bother with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With