(512) 879-9942

Syndicate

Modifying Rails URL Mapping

Maybe, instead of users going to http://yoursite/controller/view/1337, you want users to go to http://yoursite/controller/1337. In other words, you want to map the view controller to pull up by default. Here’s how to do it in Rails 2.0.2.

An Example

So let’s say you have a controller named “person” and you want the “view” action to pull up when the person fails to specify a controller (they just go to the model: i.e. http://yoursite/person/1337). Your URL map in routes.rb would look like:

map.connect 'person/:id', :controller => 'person', :action => 'view'

The Controller

Your controller will probably look something like this, at a minimum:

def view
  # Default view action.  If no ID is supplied, redirect to index.
  if(params[:id])
    # Fetch information about the person.
    @person = Person.find(params[:id])
  else
    redirect_to "http://www.yoursite.com/"
  end
end

The View

At a minimum, you’d want something like this:

<h1><%= @person.name %></h1>
...

That’s it! Restart your server and any time a person tries to enter http://yoursite/person/1337 it would be the same as pulling up http://yoursite/person/view/1337.

This entry was posted on Thu, 20 Mar 2008 11:12:59 GMT . You can follow any any response to this entry through the Atom feed. You can leave a comment .
Tags , , , ,


Comments

Leave a response

Leave a comment

© Copyright 2008 J. Austin Hughey.
aboutservicescase studiesarticlescontact