Named Routes in Rails

From Ronny Haryanto via the Rails Mailing List:


Interested in URLs that look something like this?


http://www.example.com/project/submarine


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.
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.


Thanks Ronny!

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala