0

I'm using the friendlyID rails gem which is working great at generating a new friendly url slug. My issue is that users can still access the original resource path: mydomain.com/movies/2

How would I redirect the original resource path to the new friendly Url?

Jackson Cunningham
  • 4,973
  • 3
  • 30
  • 80

1 Answers1

0

Here's how you can redirect the old :id path to your friendly_id :slug path

# config/routes.rb
get "/movies/:id", to: "movies#redirect_to_slugged_url"
get "/movies/:slug", to: "movies#show", constraints: {slug: %r{\d{4}/\d{2}/\d{2}/[^/]+}}, as: :movie


# app/controllers/movies_controller.rb
class MoviesController < ApplicationController

  def redirect_to_slugged_url
    movie = Movie.find(params[:id])
    redirect_to movie_path(movie)
  end

  def show
    @movie = Movie.friendly.find(params[:slug])
  end
end
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32