Rails always routes an action to show action, and the action it self becomes the id

There's a strange behavior in rails I found recently related to routes and actions, specifically, it's on rails 2.3.5. I have a controller, let's call it Users. In the routes, I declare Users as a resources.

map.resources :users

And within the controller, I have the standard action: index, show, edit, update & destroy. Also, I added other action to fullfil certain requirements.

def generated_pdf_report
    # do something
end

The problem is, when I go to page /users/generated_pdf_report, I get this on the console:

Processing UsersController#show (some timestamps) [GET]
  Parameters: {"action"=>"show", "id"=>"generated_pdf_report", "controller"=>"users"}

As you can see, the server route the request to method show rather than to method generated_pdf_report. What's interesting, is that I have other controllers having similar action and is working fine.

The solution to the above problem is easy enough, make sure the added feed is above the resources:

map.feed 'users/generated_pdf_report', :controller => 'users', :action => 'generated_pdf_report'
map.resources :users

My question is: Anyone knows why rails behaves like that? The above solution is kind of sloppy, what do you think the best practices for such problem like one mentioned above.

Answers


As outlined in the Rails 2 routing guide, you can add collection routes like so:

map.resources :users, :collection => { :generated_pdf_report => :get }

When rails looks at

/users/generate_report

That is exactly the path it would use to show a user whose id was generate_report, so that is what it does, assuming you haven't told it otherwise.

A shorter alternative to what you wrote is

resources :users, :collection => {:generate_report => :get}

Which tells rails to map a GET to /users/generate_report to your generate_report action


Need Your Help

Is there any publically accessible JSON data source to test with real world data?

javascript json testing treeview

I'm working on a JavaScript dynamically loaded tree view user control. I'd like to test it with real world data.

xml remove child node in php

php xml

I'm trying to remove the "druzenje" element by the 'id' attribute. I know that for that to happen, i have to remove all the child nodes from that element.