RichH RichH - 9 months ago 29
reST (reStructuredText) Question

Why do I need to work harder to make my Rails application fit into a RESTful architecture?

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.

Answer Source

If I go beyond the standard CRUD actions with my models, I normally just add the methods as required. Searching is something I add to many controllers, but not every one, so I add it and maintain the routes normally:

map.resources :events, :collection => { :search => :get }

Moving these actions to an entirely separate controller might keep some of your controllers RESTful, but I find that keeping them in context is far more useful.