前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails MVC 和 CRUD(3)

Rails MVC 和 CRUD(3)

作者头像
franket
发布2021-11-24 09:48:06
7100
发布2021-11-24 09:48:06
举报
文章被收录于专栏:技术杂记

创建一个控制器和视图

要在 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]#

进行访问

直接刷新页面

rails4.png
rails4.png

注意,我修改了配置和服务,但并没有对服务进行重启,而可以直接加载出新的内容,说明 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 也可以进行访问

rails5.png
rails5.png

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建一个控制器和视图
  • 修改页面内容
  • 设置首页
  • 进行访问
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档