views:

83

answers:

2

Hi all,

Currently we are using method_missing to catch for calls to SEO friendly actions in our controllers rather than creating actions for every conceivable value for a variable. What we want are URLS like this:

/students/BobSmith

and NOT /students/show/342

IS there a cleaner solution than method_missing?

Thank you!

A: 

You can create a catch-all route. Put this at the bottom of config/routes.rb with whatever controller and action you want:

map.connect '*path', :controller => '...', :action => '...'

The segments of the route will be available to your controller in the params[:path] array.

John Topley
What if there are other actions in the controller? Will this override those as well?
tesmar
A: 

You can define a route for that particular format fairly easily.

map.connect "/students/:name", :controller => :students, :action => :show, :requirements => {:name => /[A-Z][A-Z]+/}

Then in your show action you can find by name using params[:name].

Alan Peabody
This only works if the the names are unique. If not, then you should prefix the name with the Student's ID. Something like "/students/342-Bob-Smith" and map.connect "/students/:id". Then, just do params[:id].to_i to get the student's ID.
Michael Melanson
This seems like it would be close to what I want. In essence, this would move the current login into a different method, and then leave method_missing open for when there really was a method missing.
tesmar
Yep, keep in mind that they do have to be unique as Michael mentioned, but I really can not imagine that there is anything you can not do with the routes file and have to use method missing. You may want to look up ActiveRecord::Base.to_param method and how to create seo friendly urls with that.
Alan Peabody