# Routing through parent

**URL:** <https://www.ruby-forum.com/t/routing-through-parent/158357>\
**Category:** Rails\
**Created:** [January 22, 2009, 12:39pm UTC](https://www.ruby-forum.com/t/routing-through-parent/158357 "2009-01-22T12:39:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rmac217](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/bc8723/32.png) [@rmac217](https://www.ruby-forum.com/u/rmac217)\
**Post date:** [January 22, 2009, 12:39pm UTC](https://www.ruby-forum.com/t/routing-through-parent/158357/1 "2009-01-22T12:39:32Z")

</div>

Hello,

At the moment I have the following route in my routes.rb file

map.resources :categories do |categories|  
categories.resources :products  
end

Simple relationship…  
product belongs\_to a category  
a category has\_many products

is it possible to create a route where I could have something like:

map.product ‘/:category\_name/:product\_name’

I can’t seem to get both of the controllers working together to create  
such route.

Thanks in advance.

McKenzie

---

<div class="post-metadata">

**Author:** ![rmac217](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/bc8723/32.png) [@rmac217](https://www.ruby-forum.com/u/rmac217)\
**Post date:** [January 22, 2009, 1:02pm UTC](https://www.ruby-forum.com/t/routing-through-parent/158357/2 "2009-01-22T13:02:26Z")

</div>

On Thu, Jan 22, 2009 at 1:39 PM, Ryan M. \<  
removed\_email\_address@domain.invalid\> wrote:

> product belongs\_to a category
> 
> ## McKenzie
> 
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).
> 
> >

You can do that with map.connect ‘:category\_name/:product\_name’,  
:controller  
=\> \<controller\_name\>, :action =\> \<action\_name\>

You’ll have to think about how good an idea it is to use only category  
and  
product names and not ids

Think about using to\_param on your models which can then display both id  
and  
name  
class Category \< ActiveRecord::Base  
def to\_param  
“#{id}-#{name.gsub(/[^\w\d]+/, ‘-’)}”  
end  
end

Then you don’t have to mess with your routes and your urls will be  
/1-category/2-product and your controllers will still get the id in  
params[:id]

–  
Andrew T.  
[http://ramblingsonrails.com](http://ramblingsonrails.com)  
[http://www.linkedin.com/in/andrewtimberlake](http://www.linkedin.com/in/andrewtimberlake)

“I have never let my schooling interfere with my education” - Mark Twain
