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

如何在Ruby on Rails中构建带侧边栏的导航栏结构

Rails 侧边栏与页面路由优化实现方案

1. 配置RESTful路由

修改config/routes.rb,为SellController添加独立的collection路由,同时设置默认跳转:

resources :sell, only: [] do
  get 'sale', on: :collection
  get 'sold', on: :collection
end
# 访问/sell时自动跳转到默认的sale页面
get 'sell', to: redirect('/sell/sale')

2. 更新SellController

在app/controllers/sell_controller.rb中添加对应action,指定专属布局:

class SellController < ApplicationController
  # 指定使用sell专属布局
  layout 'sell'

  def sale
    # 编写sale页面的业务逻辑,比如获取在售商品数据
  end

  def sold
    # 编写sold页面的业务逻辑,比如获取已售商品数据
  end
end

3. 提取侧边栏为共用组件

将侧边栏代码抽成局部视图app/views/sell/_sidebar.html.erb,实现导航链接与激活状态判断:

<div class="sidebar">
  <%= link_to "在售商品", sell_sale_path, class: "#{'active' if current_page?(sell_sale_path)}" %>
  <%= link_to "已售商品", sell_sold_path, class: "#{'active' if current_page?(sell_sold_path)}" %>
</div>

4. 创建Sell专属布局

在app/views/layouts/下新建sell.html.erb,整合顶部导航与侧边栏:

<!DOCTYPE html>
<html>
<head>
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>
  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
  <!-- 复用现有顶部导航组件 -->
  <%= render 'layouts/navbar' %>

  <div class="page-container">
    <!-- 渲染侧边栏组件 -->
    <%= render 'sell/sidebar' %>
    <!-- 页面主体内容区域 -->
    <div class="main-content">
      <%= yield %>
    </div>
  </div>
</body>
</html>

5. 转换局部视图为独立页面

将原有局部视图改为独立页面模板:

  • 把_sale.html.erb内容迁移到app/views/sell/sale.html.erb
  • 把_sold.html.erb内容迁移到app/views/sell/sold.html.erb

方案优势

  • 每个页面拥有独立URL(/sell/sale、/sell/sold),符合URL语义化要求
  • 侧边栏作为共用组件,避免重复代码,激活状态自动判断
  • 布局分离,仅SellController下的页面加载侧边栏,不影响其他页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:10:18