Rails - 具有自连接模型的 SEO 友好 URL

Rails - SEO friendly URLs with Self joined models

目前有两个模型:类别和产品。类别是自连接的sub_categories。类别 has_many 产品,谁当然 belongs_to 类别。

我的问题是:如何为这些资源映射路由,以便它们具有 SEO 友好的 URL。

例如:如果用户点击 "Lamas" 类别,然后点击 "Maintenence" 子类别,最后点击 "Lama Polish" 产品。路径将是: http://lamasareawesome.com/categories/1/categories/26/products/11

我想要的是: http://lamasareawesome.com/lamas/maintenence/lama-polish

到目前为止,我不太幸运地从路径中删除控制器名称,并将其替换为模型属性。

创建使用 ID 以外的其他属性的路由非常简单。 FriendlyID 一个很好的开箱即用的解决方案,但它只会让你 URL 看起来像:

/categories/lamas/categories/maintenance/products/lama-polish

创建 URL 之类的 lamas/maintenence/lama-polish 绝对是可能的,但会很困难,因为它不是传统的并且有很多潜在的陷阱。

例如,您可以从以下内容开始:

resources :categories, path: '/' do
  resources :categories,  path: '' do
    # resources :products 
  end
end

这将创建:

                Prefix Verb   URI Pattern                      Controller#Action
   category_categories GET    /:category_id(.:format)          categories#index
                       POST   /:category_id(.:format)          categories#create
 new_category_category GET    /:category_id/new(.:format)      categories#new
edit_category_category GET    /:category_id/:id/edit(.:format) categories#edit
     category_category GET    /:category_id/:id(.:format)      categories#show
                       PATCH  /:category_id/:id(.:format)      categories#update
                       PUT    /:category_id/:id(.:format)      categories#update
                       DELETE /:category_id/:id(.:format)      categories#destroy
            categories GET    /                                categories#index
                       POST   /                                categories#create
          new_category GET    /new(.:format)                   categories#new
         edit_category GET    /:id/edit(.:format)              categories#edit
              category GET    /:id(.:format)                   categories#show
                       PATCH  /:id(.:format)                   categories#update
                       PUT    /:id(.:format)                   categories#update
                       DELETE /:id(.:format)                   categories#destroy

但是有一个超大陷阱 - 假设请求是

GET /lamas/joe-the-lama

Rails 怎么知道这个请求应该由 LamasController 而不是 CategoriesController 处理?您将不得不对两者进行数据库查询。当然,如果你总是有两个类别,这不是问题,但你明白我的意思 - 事情很快就会变得复杂。

标准Rails 样式restful 路由可能有点冗长,但它确实避免了很多潜在的歧义。