【发布时间】:2016-03-23 08:15:34
【问题描述】:
我正在使用friendlyID rails gem,它非常适合生成新的友好 url slug。我的问题是用户仍然可以访问原始资源路径:mydomain.com/movies/2
如何将原始资源路径重定向到新的友好 URL?
【问题讨论】:
我正在使用friendlyID rails gem,它非常适合生成新的友好 url slug。我的问题是用户仍然可以访问原始资源路径:mydomain.com/movies/2
如何将原始资源路径重定向到新的友好 URL?
【问题讨论】:
以下是如何将旧的 :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
【讨论】: