views:

544

answers:

3

Hi,

I have a set of routes that are generated dynamically at runtime, but that all point to the same controller i.e.

map.resources :authors, :controller => 'main'
map.resources :books, :controller => 'main'

These all work fine, producing routes like /authors/1, /books, /books/55, etc and then all end up being processed by the 'main' controller.

However, I can't seem to find how to get the name of the resource in the controller i.e. in the index action when the URL is /authors or /books I'd like to be able to determine which resource it is, i.e. Author or Book

I cannot use separate controllers for this.

Is this at all possible ?

A: 

I don't think there's anything like a .resource method, but you could look at request.request_uri, which in your case would return things like /authors or /books, and could act accordingly.

Terry
+2  A: 

EDIT: complete change of answer because it was waaay off.

So because it changes the params that you see in your action you'll have to get at the actual uri. It is really just as simple as what Terry suggested.

 def index
   if request.request_uri =~ /books/
     #...
   else
     # if it is a author
   end
 end

This compares the request uri (the part that would be after localhost:3000) to books and so you can see what the user has requested.

vrish88
As I stated in my question, I use the same controller for both routes (main) so using the method you describe returns the name of the custom controller, not the name of the resource. In this case, main.
Ah, ok thanks for letting me know. I updated my answer so that it will actually answer your question ;)
vrish88
A: 

See the "Defaults routes and default parameters" section of the ActionController::Routing documentation. You can program into your routes arbitrary extra parameters you would like sent to your controller.

Looking at the request URI will force you to keep routes and controllers in sync, which will make your code more fragile and less easily re-used. Avoid if you possibly can.

asplake