创建一个控制器和视图
要在 Rails 中显示“My first test” 的静态页面,需要新建一个控制器和视图
控制器用来接受向程序发起的请求
视图的作用是,以人类能看懂的格式显示数据
代码语言:javascript复制[root@h202 blog]# rails generate controller welcome index
Running via Spring preloader in process 11871
create app/controllers/welcome_controller.rb
route get 'welcome/index'
invoke erb
create app/views/welcome
create app/views/welcome/index.html.erb
invoke test_unit
create test/controllers/welcome_controller_test.rb
invoke helper
create app/helpers/welcome_helper.rb
invoke test_unit
invoke assets
invoke coffee
create app/assets/javascripts/welcome.coffee
invoke scss
create app/assets/stylesheets/welcome.scss
[root@h202 blog]#
修改页面内容
代码语言:javascript复制[root@h202 blog]# vim app/views/welcome/index.html.erb
[root@h202 blog]# cat app/views/welcome/index.html.erb
<h1>My first test</h1>
<p>Find me in app/views/welcome/index.html.erb</p>
[root@h202 blog]#
设置首页
路由决定哪个控制器会接受到这个请求
代码语言:javascript复制[root@h202 blog]# vim config/routes.rb
[root@h202 blog]# grep -v " #" config/routes.rb | grep -v "^$"
Rails.application.routes.draw do
get 'welcome/index'
root 'welcome#index'
end
[root@h202 blog]#
进行访问
直接刷新页面
注意,我修改了配置和服务,但并没有对服务进行重启,而可以直接加载出新的内容,说明 Rails 可以进行动态加载
In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server.
下面是访问过程中产生的日志
代码语言:javascript复制Started GET "/" for 192.168.100.1 at 2016-04-22 20:13:15 0800
Cannot render console from 192.168.100.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by WelcomeController#index as HTML
Rendered welcome/index.html.erb within layouts/application (0.1ms)
Completed 200 OK in 38ms (Views: 37.0ms | ActiveRecord: 0.0ms)
使用 http://192.168.100.202:3000/welcome/index
也可以进行访问