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

Rails初学者求助:如何创建路径为requirements/major的视图?

如何创建requirements/major路径的视图?

步骤1:添加路由

在你的routes.rb里,添加对应requirements/major的路由规则,有两种常用方式:

方式一:直接添加get路由

直接指定路径和对应的控制器动作:

Rails.application.routes.draw do
  resources :requirements
  get "requirements/major", to: "requirements#major" # 新增这条路由
  root "department#index"
  get "department/about"
end

方式二:扩展resources的集合路由

如果这个动作是针对requirements集合的操作,可以用collection块整合到资源路由中:

Rails.application.routes.draw do
  resources :requirements do
    collection do
      get :major # 自动生成`requirements/major`路径
    end
  end
  root "department#index"
  get "department/about"
end

步骤2:在控制器中添加对应动作

打开app/controllers/requirements_controller.rb,新增major方法,可在其中添加视图需要的业务逻辑:

class RequirementsController < ApplicationController
  # 保留原有控制器方法...

  def major
    # 示例:传递数据到视图
    # @requirements = Requirement.all
  end
end

步骤3:创建视图文件

在app/views/requirements目录下创建major.html.erb文件(若使用其他模板引擎,对应创建major.slim/major.haml等),编写视图内容:

<h1>专业需求页面</h1>
<!-- 在这里添加你的HTML/ERB代码 -->

完成以上三步后,访问http://localhost:3000/requirements/major就能看到对应的视图了。

内容的提问来源于stack exchange,提问作者Thai Nam Hoang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:30:59