You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用current_page?为导航链接添加active类时根路径匹配失败的解决方法

修正Rails根路径下导航链接的Active类问题

当前的问题是:根路由指向pages#work,访问根路径/时,Work导航链接没有被添加active类,但访问/work和/about时,对应链接的active类能正常生效。

解决方案:修改辅助方法,同时匹配根路径与目标路径

把现有的辅助方法调整为,当判断Work页面路径时,同时覆盖根路径和/work路径:

def active_class(link_path)
  if link_path == work_path
    current_page?(link_path) || current_page?(root_path) ? "active" : ""
  else
    current_page?(link_path) ? "active" : ""
  end
end

也可以用更灵活的数组写法,统一管理需要匹配的路径:

def active_class(link_path)
  matching_paths = [link_path]
  # 给Work页面追加根路径作为匹配项
  matching_paths << root_path if link_path == work_path
  current_page?(*matching_paths) ? "active" : ""
end

原因说明

current_page?(work_path)只会严格匹配/work路径,而根路径/对应的是root_path,所以需要让Work链接的active判断逻辑同时覆盖这两个路径,这样无论用户访问/还是/work,Work链接都会被加上active类。

内容的提问来源于stack exchange,提问作者rcrusoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:05:23