How to add a new action to the Rails 3.2 controller

If you want to add a new controller action to Ruby on Rails controller, you can do by adding the following bit of code.

1st: to the controller file, you add a new action, like:

def myaction
 // hackhackhack
end

Then in your routes.rb file, you add the route (in the section where you define this resource):

resource :myresource do
  collection do
    get 'myaction'
  end
end

More details here.

How did I come to do this?

I am coding together a nice little proof-of-concept app in rails. In this, I have a simple model with standard RESTful controller actions, GET/PUT/POST/DELETE matching new/edit/update/destroy actions in addition to collection type index action.

I needed another action, one that would just list selected properties of those objects (kind of like index but not quite so).

 

Leave a Reply