Rails中如何更新params或重定向到带slug的正确URL?
Rails 带slug后缀URL的访问处理方案
方案1:301重定向到规范URL(推荐)
该方案可以避免重复URL对SEO的负面影响,是Rails生态的常规实现方式:
- 首先在对应Model中重写
to_param方法,生成符合你要求的slug格式(假设你的数据模型名为TestItem,名称字段为name):
class TestItem < ApplicationRecord # 重写to_param方法,生成 id-名称 格式的路由参数 def to_param "#{id}-#{name.parameterize}" end end
parameterize方法会自动将字符串转换为URL友好的格式,自动替换空格、特殊字符为连接符。
- 在对应控制器的处理动作中加入校验重定向逻辑:
class TestController < ApplicationController def testing # 提取请求参数中纯数字的ID部分 real_id = params[:id].split('-').first @test_item = TestItem.find(real_id) # 比对当前请求的id参数和规范的slug格式,不一致则重定向 if params[:id] != @test_item.to_param redirect_to test_testing_path(@test_item), status: :moved_permanently end # 后续正常的业务逻辑 end end
路由不需要额外修改,Rails默认的:id参数匹配规则会自动匹配带横杠的slug内容。
方案2:直接修改params参数(不推荐)
如果你不需要做URL规范,只想在页面加载前修正params值,可以在查询到对应数据后直接覆盖params参数:
def testing real_id = params[:id].split('-').first @test_item = TestItem.find(real_id) # 直接修改params的id值 params[:id] = @test_item.to_param # 后续业务逻辑 end
该方案的缺点是同一个内容会对应多个可访问的URL,不利于搜索引擎收录。
补充说明
如果你的名称字段包含中文,默认的parameterize方法无法正常转换,可以使用第三方slug生成工具处理。
内容的提问来源于stack exchange,提问作者fev3r
相关产品推荐
相关产品推荐

