Rails& FriendlyID gem:如何将资源路径重定向到新的友好URL

时间:2015-12-17 00:42:41

标签: ruby-on-rails friendly-id

我正在使用friendlyID rails gem,它可以很好地生成一个新的友好url slug。我的问题是用户仍然可以访问原始资源路径:mydomain.com/movies/2

如何将原始资源路径重定向到新的友好网址?

1 个答案:

答案 0 :(得分:0)

以下是如何将old:id路径重定向到friendly_id:slug路径

# 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