Rails快速上手

Windows下安装Ruby和InstantRails
http://instantrails.rubyforge.org/wiki/wiki.pl下载InstantRails并解压到一个目录
由于InstantRails自身就包含了Ruby解释器,所以不用另外再下载Ruby的Windows安装程序
运行InstantRails.exe,提示是否更改路径配置,选择是。

创建一个新程序
点击InstantRails窗口左上角的"I"->Rails Applications->Open Ruby Console Window
这时会打开一个位于InstantRails/rails_apps目录的Console,输入命令:

代码
  1. rails demo   

<script type="text/javascript">render_code();</script>
该命令创建了一个叫demo的程序,并创建了demo目录
demo目录下有README和Rakefile文件和app/compoments/config/db/doc/lib/log/public/script/test/tmp/vendor子目录
运行cd demo进入demo目录,然后运行以下命令:

代码
  1. ruby script/server   

<script type="text/javascript">render_code();</script>
你将看到Ruby自带的WEBrick服务器在localhost的3000端口启动了,现在打开浏览器看看效果http://localhost:3000

 

创建Controller
现在让我们创建一个Controller,运行以下命令:

代码
  1. ruby script/generate controller Say   

<script type="text/javascript">render_code();</script>
我们会看到系统又生成了一堆文件和目录,其中主要的文件为app/controllers/say_controller.rb
让我们编辑该文件:

代码
  1. class SayController < ApplicationController   
  2.     def hello   
  3.         @time = Time.now   
  4.     end   
  5.        
  6.     def goodbye   
  7.     end   
  8. end   
<script type="text/javascript">render_code();</script>

 

创建rhtml模板
Ruby的MVC框架中URL、Controller和模板映射很直接
如http://xx.xx.xx/aa/bb这个URL将访问aa这个Controller的bb方法,而bb方法的页面模板为views/aa/bb.rhtml
这是Rails默认配置下的映射
我们在SayController类中定义了hello和goodbye方法,下面我们创建它们对应的模板
1,views/say/hello.rhtml

代码
  1. <html>  
  2.     <head>  
  3.         <title>Hello, Rails!</title>  
  4.     </head>  
  5.     <body>  
  6.         <h1>Hello from Rails!</h1>  
  7.         <p>  
  8.             It is now <%= @time %>  
  9.         </p>  
  10.         <p>  
  11.             Time to say   
  12.             <%= link_to "Goodbye!", :action => "goodbye" %>  
  13.         </p>  
  14.     </body>  
  15. </html>  

<script type="text/javascript">render_code();</script>
2,views/say/goodbye.rhtml

代码
  1. <html>  
  2.     <head>  
  3.         <title>See You Later!</title>  
  4.     </head>  
  5.     <body>  
  6.         <h1>Goodbye!</h1>  
  7.         <p>  
  8.             It was nice having you here.   
  9.         </p>  
  10.         <p>  
  11.             Say <%= link_to "Hello!", :action => "hello" %> again.   
  12.         </p>  
  13.     </body>  
  14. </html>  

<script type="text/javascript">render_code();</script>
其中link_to()辅助方法将创建到一个action的链接,如<%= link_to "Hello!", :action => "hello" %>将被ERB解析成<a href="/say/hello">Hello!</a

 

启动Rails自带服务器WEBrick测试
由于刚才已经启动了WEBrick,现在直接访问http://localhost:3000/say/hello即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值