views:

306

answers:

1

I would like to be able to map URLs to Controllers dynamically based on information in my database.

I'm looking to do something functionally equivalent to this (assuming a View model):

map.route '/:view_name',
    :controller => lambda { View.find_by_name(params[:view_name]).controller }

Others have suggested dynamically rebuilding the routes, but this won't work for me as there may be thousands of Views that map to the same Controller

+1  A: 

So I think that you are asking that if you have a Views table and a View model for it where the table looks like

id | name | model
===================
1  | aaa  | Post
2  | bbb  | Post
3  | ccc  | Comment

You want a url of /aaa to point to Post.controller - is this right?

If not then what you suggest seems fine assuming it works.

You could send it to a catch all action and have the action look at the url, run the find_by_name and then call the correct controller from there.

def catch_all
  View.find_by_name('aaa').controller.action
end

Update

You can use redirect_to and even send the params. In the example below you I am sending the search parameters

def catch_all
  new_controller = View.find_by_name('aaa').controller
  redirect_to :controller => new_controller, :action => :index, 
      :search => params[:search] 
end
Will
How do you "call the correct controller"? Rails maintains instances of each controller and sets up Requests contexts, populates `params`, and lots of other stuff, how do I instruct rails to forward the request from within one controller to another one?
Daniel Beardsley
See my update above
Will
redirect_to will send a [302 HTTP](http://en.wikipedia.org/wiki/HTTP_302) response to the client, causing the browser to re-request the new URL. This isn't what we want.
Daniel Beardsley
You used to be able to use render_component in pre rails 2.3 but if you still want to do that then checkout the http://github.com/rails/render_component plugin
Will