创建和认识Ruby On Rails控制器
我们都知道Ruby On Rails是一个MVC结构的框架。必然他的控制器,视图,数据都是分开的,我们将对他们进行分解,逐个了解他们。首先我们使用命令先创建一个控制器:
注意:控制器名和方法名称请使用小写
# bin/rails generate 控制器名称 方法名称 --skip-routes
bin/rails generate articles index --skip-routes
执行结果:
create app/controllers/articles_controller.rbinvoke erbcreate app/views/articlescreate app/views/articles/Index.html.erbinvoke test_unitcreate test/controllers/articles_controller_test.rbinvoke helpercreate app/helpers/articles_helper.rbinvoke test_unit
通过执行脚本,rails框架已经为我们创建了一个控制器所需要的完整文件。
控制器文件:app/controllers/Articles_controller.rb,
视图文件:app/views/Articles/index.html.erb,
单元测试文件:test/controllers/Articles_controller_test.rb。
因为我们想要自己添加路由,所以创建的时候使用了 –skip-routes参数。接下来我们自己添加路由,在编辑器中打开 config/routes.rb 文件,在 do 到 end 之间添加 get ‘articles/index’ 。
Rails.application.routes.draw doget 'articles/index'# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
可以使用命令启动服务进行检查。
bin/rails server
当我们看到以下返回时,服务器成功启动,你可以在浏览器中请求 http://localhost:3000 访问刚刚创建的请求。
=> Booting Puma
=> Rails 7.1.3.2 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 6.4.2 (ruby 3.1.2-p20) ("The Eagle of Durango")
* Min threads: 5
* Max threads: 5
* Environment: development
* PID: 108
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop
打开app/controllers/articles_controller.rb控制器文件,我们查看一下他的代码。
class ArticlesController < ApplicationControllerdef indexend
end
打开视图文件app/views/Articles/index.html.erb:
<h1>Articles#index</h1>
<p>Find me in app/views/articles/index.html.erb</p>
控制器 ArticlesController 继承于 ApplicationController,他只有一个方法 index。里没没有任何别的代码。什么代码都没有书写,但是框架自动为我们渲染了对应的视图文件。为什么会是这样子?因为 Ruby On Rails 框架是一个约定优先于配置的 MVC 结构的框架,使用约定来代替XML配置文件说明Rails本身完成了大量的底层工作,这意味着使用更少的代码来实现应用程序是极有可能的。此外,代码量的缩减也减小了出现bug的可能性,降低了维护程序和升级程序的难度。
所以后面使用 Ruby On Rails 框架进行应用开发时,他将有助于帮助我们使用更少的代码实现更健壮的程序。