【问题标题】:Rails & FriendlyID gem: how to redirect resource path to new friendly URLRails & FriendlyID gem:如何将资源路径重定向到新的友好 URL
【发布时间】:2016-03-23 08:15:34
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails friendly-id


    【解决方案1】:

    以下是如何将旧的 :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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2018-07-01
      • 2014-11-13
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多