Named Routes in Rails

From Ronny Haryanto via the Rails Mailing List:

Interested in URLs that look something like this?

You can tell Rails to parse that URL in order to call the appropriate method on the controller.

 You might be interested in Named Routes.

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]])

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.

Thanks Ronny!

Post a Comment

Popular posts from this blog

Converting Array to List in Scala

I ported a JavaScript app to Dart. Here's what I learned.

Null-aware operators in Dart