I have a list of 1000+ cities, I would like to generate routes for each city, e.g:
www.example.com/NewYork-Cinemas
www.example.com/Boston-Cinemas
would redirect to:
www.example.com/city_id=1234
www.example.com/city_id=1235
How can I add these types of routes to the routes.rb file?
Thanks
You'll need to consider two important factors:
- Your routes should be
resourceful
- Using "slugs" in your routes is the role of third-party extensions
Here's how to acheive what you want:
Routes
#config/routes.rb
resources :cities, path: "", only: :show #-> domain.com/:id
#app/controllers/cities_controller.rb
class CitiesController < ApplicationController
def show
@city = City.find params[:id]
end
end
The above routes might not be what you wanted, but they'll do something very important - they'll give you a resourceful structure (which maintains the convention of Rails):
I like posting this picture a lot - most people don't know it exists. You can find it here -- it explains how you should keep your routes resourceful. Other answers just recommended creating a new custom route - bad news. You need to keep your routes structured as possible, otherwise they become unwieldy
Find
Secondly, you'll want to heed the recommendation of another answer, and employ the use of friendly_id
in your app:
#app/models/city.rb
class City < ActiveRecord::Base
extend FriendlyID
friendly_id :name, use: [:slugged, :finders]
end
This will give you the ability to use the "slug" name in your title. Friendly ID will automatically take care of the entire process - you can watch a Railscast about it here if you want.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments