Routing Requests with a database field


#1

Hello.

I am building a website that has a growing list of projects. So lets say
I’d
like to go to http://localhost:3000/project/submarine/ and view the
“Submarine Project”. I’d have a database, and an entry could be. id=1,
title=submarine, description=we built a submarine. I’ve been reading
through
the pragprog rails book and asking in the #rubyonrails irc channel, but
I
can’t find the answer anywhere. I couldn’t even find anything on google.

Any help is greatly appreciated.

Good day,
Matt


#2

On Tue, Nov 15, 2005 at 10:21:42PM -0500, Matt R. wrote:

I am building a website that has a growing list of projects. So lets
say I’d like to go to http://localhost:3000/project/submarine/ and
view the “Submarine Project”. I’d have a database, and an entry
could be. id=1, title=submarine, description=we built a submarine.
I’ve been reading through the pragprog rails book and asking in the
#rubyonrails irc channel, but I can’t find the answer anywhere. I
couldn’t even find anything on google.

You might be interested in Named Routes.
http://wiki.rubyonrails.com/rails/pages/NamedRoutes

In config/routes.rb:

map.project 'project/:projtitle' :controller => 'project',
			     :action => 'show'

In app/controllers/project_controller.rb:

def show
  @project = Project.find(:first,
  			      :conditions => ['title = ?',params[:projtitle]])
  ...
end

Or something like that. Assuming your project titles are unique. Then
you can also use project_url (since you have map.project in routes.rb)
for urls in your views, e.g.

<% for project in @projects %>
<%= link_to project.title,
            project_url(:projtitle => project.title) %>
 ...
<% end %>

Named Routes is a really cool feature, and one of the best of Rails,
I’d say.

Ronny


#3

Thanks a lot. I’ll give that a shot tomorrow sometime, and I’ll probably
post back because I know absolutely nothing.