0

FriendlyID is consistently showing duplicate content for both /slug and /1. In other words, the correct page is loading for the friendly slug (/new-york), but it's loading the same content for the old, unfriendly slug (/11).

Here's my current configuration:

#config/routes.rb
resources :groups, path: ''
get 'groups/:id' => redirect("/%{id}")

#app/models/group.rb
class Group < ActiveRecord::Base
   extend FriendlyId
   friendly_id :name, use: [:slugged, :finders]
end

#app/controllers/groups_controller.rb
def show
    @group = Group.friendly.find(params[:id])
end

As a potential workaround, I've found putting this in my controller does redirect the bad slugs (/11) to the good slugs (/new-york), but it feels wrong for many reasons (routing outside routes.rb, likely unintended consequences, complex solution for a common problem = probably not the right one).

    if request.path != group_path(@group)
      return redirect_to @group, :status => :moved_permanently
    end

What is the right way to make FriendlyID either (1) redirect :id calls to :slug or (2) simply 404 them?

Antonio Fergesi
  • 151
  • 1
  • 9

1 Answers1

0

Thanks to this fantastic comment on Medium, I now have a fully functional and very elegant solution which solves my initial problem (duplicate pages with /new-york and /11) as well as allowing two root-level slug structures to coexist.

get '/:id', to: 'groups#show', constraints: proc {|req| FriendlyId::Slug.where(sluggable_type: 'Group').pluck(:slug).include?(req.params[:id])}, as: :group
get '/:id', to: 'custom_pages#show', constraints: proc {|req| FriendlyId::Slug.where(sluggable_type: 'CustomPage').pluck(:slug).include?(req.params[:id])}, as: :custom_page
Antonio Fergesi
  • 151
  • 1
  • 9