我现在致力于网站 SEO 优化,我需要做的是正确路由链接,使其对 SEO 非常友好。我已经阅读了很多关于路由的信息,但它在我的脑海里乱七八糟,我卡住了。
所以我有 Store 模型,它属于 StoreType 模型、City 模型和 District 模型 + District belongs_to :city。
我需要这样的路线:
/stores/store_type_name/ - store_type 'show' action(list of stores by type)
/stores/city_name/store_type_name/ - store_type 'show' action(list of stores by city&type)
/stores/city_name/district_name/store_type_name/ - store_type 'show' action(list of stores by city&district&type)
/stores/city_name/store_type_name/store_name - store 'show' action
我目前想到的唯一解决方案是: 路线.rb
namespace :stores do
get ':transliterated', to: 'store_types#show'
get ':transliterated/:name_en', to: 'store_types#city'
get ':transliterated/:name_en/:id', to: 'store_types#district'
end
像这样的 Controller :
def district
@store_type = StorerType.find_by_transliterated(params[:transliterated])
@city = City.find_by_name_en(params[:name_en])
@district = District.find_by_id(params[:id])
if @store_type && @city && @district
stores = @store_type.stores.where(city_id:@city.id)
@stores = stores.where(district_id:@district.id)
else
redirect_to root_path
end
end
效果很好,但是 1) 我现在无法为最后一个示例(商店展示页面)添加路由,因为路由正在该命名空间中寻找 :transliterated 参数,如果找不到记录则重定向。 2)我知道这个解决方案不好,可以做得更好,我只是不知道怎么做。请给我一个建议。
附言。实际上网站上已经实现了路由,所以我正在寻找上面列出的那 4 个 url 的解决方案,而没有触及那里的任何其他内容。
最佳答案
足智多谋
首先,让我为您定义所有路由的基础...
Rails 的路由结构被称为 resourceful - 意味着基于 around 资源/对象。正如 Ruby 是一个 object-orientated language ,Rails是一个面向对象的框架;路线也不异常(exception):
这意味着您对路由所做的任何事情都是基于资源的,如下所示:
#config/routes.rb
namespace :stores do
resources :store_types, only: [:show], path: "" do #-> domain.com/stores/:id -> store_types#show
get :name_en, action: :city #-> domain.com/stores/:store_type_id/:name_en
get :name_en/:id, action: :district #-> domain.com/stores/:store_type_id/:name_en/:id
end
end
这将使您能够将流量直接发送到您的 store_types
Controller ,而无需到处都是各种疯狂的路线
--
friendly_id
另外要考虑的是一个名为 friendly_id
的 gem
friendly_id
基本上允许您使用 slugs
定义/调用路由,而不是 id
。不同之处在于路由保持不变 - 是数据,以及对数据的处理,它发生了变化
通常在 Rails 中,您将创建这样的路由:domain.com/controller/:id
例如,当您将人们发送到链接时,他们会点击 domain.com/controller/1
。 Friendly_ID 基本上提供了将人们发送到 domain.com/controller/your_name
的能力,处理方式与使用 ID 完全相同:
#app/models/your_model.rb
Class YourModel < ActiveRecord::Base
friendly_id :name, use: [:slugged, :finders]
end
这将允许您调用:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def show
@model = Model.find params[:id]
end
end
关于ruby-on-rails - Rails 4. 少数模型的不同路由(相关和不相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25136018/