第一是创建demo:命令行进入任意目录,建立自己的demo目录,之后执行 rails new appdemo 就会再该目录下生成你的rails工程。名字为appdemo
第二执行demo: cd到该demo目录下,$rails s就会开启该服务,在浏览器输入地址127.0.0.1:3000,或http://localhost:3000就可以访问了,出现Welcome aboard!
第三试着做基本的更改demo显示信息:首先了解一点rails也是mvc的模式,在 app/controllers目录下生成控制器,然后在 app/views目录下生成view(当中是html标签)。一般是用控制器的名字作为views的路径名字。最后在config/routes.rb文件中增加访问路由,就可以正常访问了。
在demo目录下执行rails g controller mytest2 index命令,会产生如下信息可以看到创建了一些文件:
create app/controllers/mytest2_controller.rb
route get "mytest2/index"
invoke erb
create app/views/mytest2
create app/views/mytest2/index.html.erb
invoke test_unit
create test/controllers/mytest2_controller_test.rb
invoke helper
create app/helpers/mytest2_helper.rb
invoke test_unit
create test/helpers/mytest2_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/mytest2.js.coffee
invoke scss
create app/assets/stylesheets/mytest2.css.scss
我们打开app/views/mytest2/index.html.erb文件进行修改就会显示我们想要的内容了。例如改为
<h1>hello,rails</h1>,则访问http://localhost:3000/mytest2/index就会显示hello,rails了。
值得注意的是 config/routes.rb文件中增加的 route get "mytest2/index"这句话,是增加路由,这样才能保证我们输入了上述地址能访问到我们修改的内容哦。 如果我们不想增加后面的/mytest2/index而通过直接访问http://localhost:3000实现访问修改的内容怎么做呢,简单,还是在路由文件中修改为:root:to=>"mytest2#index" 就可以了哦。
稍微复杂一点的例子,弄几个变量哈哈。在控制器mytest2_controller.rb中加入:
#coding: utf-8
class Mytest2Controller < ApplicationController
def index---定义的函数
@test="hello你好"---定义的变量
who="myself"
puts @test+"ceshi"+who
end
end
然后在app/views/mytest2/index.html.erb中改为:
<h1><%=@test%></h1>
重新启动服务 ctrl+c ,然后执行rails s重新启动服务就可以显示hello 你好了。