如何修复:id和:slug的FriendlyID重复内容

时间:2019-01-07 11:03:57

标签: friendly-id

FriendlyID始终显示/ slug和/ 1的重复内容。换句话说,对于友好的子弹(/ new-york),正确的页面正在加载,但是对于不友好的老子弹(/ 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

作为一种可能的解决方法,我发现将其放在控制器中确实会将不良子弹(/ 11)重定向到不良子弹(/纽约),但是由于许多原因(在route.rb外部路由)感觉不对,可能会带来意想不到的后果,对一个常见问题的复杂解决方案=可能不合适)。

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

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

1 个答案:

答案 0 :(得分: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