Saturday, August 23, 2008

Custom Actions

Adding Custom Actions

Let's say that you have a students model/view/controller. You can start by doing things like:




http://localhost:3000/studentsuses index.html.erb, def index
http://localhost:3000/students/newuses new.html.erb, def new
http://localhost:3000/students/1uses show.html.erb, def new
Let's say you also want to get one of the following urls working ...
  • http://localhost:3000/students/feedme
  • http://localhost:3000/students/1/feedme

What's happening is that you are requesting a custom action called "feedme." (Normally Ruby's restful interface only allows 7 actions, see more commentary below).

Let me show you how to add custom actions.

Getting http://localhost:3000/students/feedme Working

Step 1:
To class StudentsController add a method:
def feedme
#do something here...
end

Step 2:
To app/views/students/ folder add the following file:
feedme.html.erb
and write the html you want to execute.

Step 3:
To your routes.rb file add
map.resources :students, :collection => {:feedme => :get}

Read the above line something like this: Add a custom action called "feedme" that empoys a http "get" request on the students model.

Note that you will likely already have "map.resources :students" in the routes.rb file to start.

Getting http://localhost:3000/students/1/feedme Working

Do the exact same steps except the routes.rb file should include

map.resources :students, :member => {:feedme => :get}


WARNING

Creating a custom action ought to be done sparingly. Ruby's latest incarnation enforces a restful architecture - part of which includes a uniform interface for all your controls. When you add custom controls you break the uniform interface on this model - so do it only when necessary!

Futher resources:

No comments: