Creating SEO friendly URLs in Rails 3
Asked Answered
N

2

5

I currently have URLs which look like this:

things?category_id=6&country_id=17

and I would like to have URLs which look like this:

/printer_cartridges/united_kingdom

Is there a way in Rails 3, without hard coding all of the categories and countries in the router to have the URLs as I would like above, perhaps using find_by_name or the such like? What is the best way to approach this?

Nunhood answered 14/2, 2011 at 18:20 Comment(1)
Read the Rails Guide on routing, especially Nested Resources: guides.rubyonrails.org/routing.html#nested-resourcesScherzo
L
4
match '/:category_slug/:country_slug', :to => 'things#index'

Then you'll need to update your action to look up everything using params[:category_slug] and params[:country_slug] instead of the ids. Look at the slugged gem to generate slugs.

Lazo answered 14/2, 2011 at 18:33 Comment(1)
Sutto's slugged gem is the way to go on this. Thanks Jordan.Nunhood
R
3

In your category model add the method

def to_param
   "#{category_name.parameterize}/#{location_name.parameterize}"
end

where category_name and location_name are where you input where you have have the names stored.

Rourke answered 14/2, 2011 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.