Reputation: 599
I have a list of cities stored in City
table. Let's say I want to generate dynamic routes to be accessible through resource.name
, city.name
in this example.
I want to be able to visit /amsterdam
or /berlin
. How?
For info I'm using friendly_id gem so already have slug column if that makes more sense.
Upvotes: 1
Views: 2264
Reputation: 1414
Don't know if this helps .. but I have put together a gist on what I use in my projects.
https://gist.github.com/1908782
It mostly works for what I do as my routes file is generally quite concise.
The beauty of it is, that if you attempt to visit a path that doesn't exist, it won't hit any routes!
Just a side note, this is broken in the 4.0 release. At the time of writing this, you will need to put the following in your gemfile.
gem 'friendly_id', :git => 'git://github.com/norman/friendly_id.git'
or
gem 'friendly_id', :git => 'https://github.com/norman/friendly_id.git'
Hope this helps.
Upvotes: 0
Reputation: 4419
At the end of your routes file, add this:
match '*id' => 'cities#show
Then in your CitiesController:
def show
@city = City.find(params[:id])
# ...
end
Upvotes: 0
Reputation: 46703
Assuming you have friendly_id set up correctly:
match '/cities/:name' => 'cities#show'
or
resources :cities
From the Quick Start for the friendly_id gem:
class City < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
end
Also:
# If you're adding FriendlyId to an existing app and need
# to generate slugs for an existing model, do this from the
# console, runner, or add a Rake task:
City.find_each(&:save)
Here is a RailsCast on it: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast
Upvotes: 4