【问题标题】:How to fix FriendlyID duplicate content for :id and :slug如何修复 :id 和 :slug 的 FriendlyID 重复内容
【发布时间】:2019-01-07 11:03:56
【问题描述】:

FriendlyID 始终显示 /slug 和 /1 的重复内容。换句话说,正确的页面正在为友好的 slug (/new-york) 加载,但它正在为旧的、不友好的 slug (/11) 加载相同的内容。

这是我当前的配置:

#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

作为一种潜在的解决方法,我发现将它放在我的控制器中确实会将坏 slug (/11) 重定向到好 slug (/new-york),但由于多种原因感觉错误(路由外部 routes.rb , 可能的意外后果, 常见问题的复杂解决方案 = 可能不是正确的解决方案。

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

使 FriendlyID 成为 (1) 将 :id 调用重定向到 :slug 或 (2) 简单地对其进行 404 处理的正确方法是什么?

【问题讨论】:

    标签: friendly-id


    【解决方案1】:

    感谢this fantastic comment on Medium,我现在有了一个功能齐全且非常优雅的解决方案,它解决了我最初的问题(使用 /new-york 和 /11 的重复页面)以及允许两个根级 slug 结构共存。

    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
    

    【讨论】:

      猜你喜欢
      • 2014-11-19
      • 1970-01-01
      • 2018-04-09
      • 2014-12-10
      • 2013-03-29
      • 2015-01-27
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多