Let's say you have a model Speaker that utilizes FiendlyId gem to create unique slugs like this:
class Speaker < ApplicationRecord
friendly_id :name, use: %i[slugged history finders]
end
And you are using CanCanCan gem to implement authorization in your application. So, in your SpeakersController you are loading and authorizing the resources like this:
class SpeakersController < ApplicationController
load_and_authorize_resource
# GET /speakers
def index; end
# GET /speakers/1
def show; end
end
And you are using the same method to load and authorize resources in other controllers.
How you can utilize the history plugin from FiendlyId gem to redirect your old slugs like /speakers/falde-ali to new slugs like /speakers/ali-fadel when you change the speaker name, without implementing a specific method inside each controller to handle it?
Basically, you can implement a concern inside
app/controller/concernslike this:Then include it into your controllers below the load and authorization call, like this:
This concern implements a redirect to the latest slug using the FriendlyId gem.
The concern includes a
before_actionthat calls theredirect_to_canonical_routemethod. This method retrieves the record from the controller's instance variables, then generates a canonical path using thepolymorphic_pathmethod. If the current request path doesn't match the canonical path, the method issues a permanent redirect to the canonical path usingredirect_to.This concern provides a way to ensure that URLs with old or outdated slugs are redirected to the latest version of the URL. This can be helpful for maintaining SEO and ensuring that users are always directed to the correct page.
I hope it is helpful :)