Welcome to Delicate template
Header
Just another WordPress site
Header

REST design with extra actions

July 28th, 2008 | Posted by Michaël in ICT | Ruby On Rails | Web Development

Yesterday, I had to add some extra actions in my controllers, so I could view some charts. The problem was that Rails didn’t recognize the actions, becouse Rails sees you action name as an id.

But Rails wouldn’t be Rails if it didn’t had a clever solution. Lets say you have a a resource called “Resource” and a similar controller. You want to add a new action and view to the resource controller named “charts” .

Just open your routes.rb file and find the line where you map the resource and add the following:

1
  map.resources :resource, :collection => [:charts], :member => [:print_pdf]

For the sake of being complete, if have added a member. The diffrence between a collection and a member is that collections work on all items of that resource (no id needed, like index action),
so:

1
  charts_resources_path()

could be used and give you a page with covering the charts of all resources

while a member works on a single item of the resource, defined by it’s id

1
print_pdf_resource_path(1234)

would print the resource with id 1234 as pdf

of course like with all other REST actions (or CRUD actions, to be correct) you can use additional named params like:

1
2
chart_resources_path(:type => :monthly)
print_pdf_resource_path(1234, :font => "Arial")

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">