Ruby On Rails 的 HelloWorld

继上回启好服务器,能看到rails的页面后,可以开始Hello World了。

Rails是典型的MVC,并且可以用他的脚手架工具直接生成Controller代码:
cd到工程下 执行 ruby script/rails generate controller Helloworld

可以看到生成了控制器代码 app/controllers/helloworld_controller.rb ….
这是一个集成了ApplicationController的控制器

class HelloworldController < ApplicationController
end

给他加上点东西

class HelloworldController < ApplicationController
def Hello
end
end

代表控制器跳转到Hello,随后到app/views/helloworld 建立页面模板 rhtml文件hello.rhtml,这个页面文件对应控制器里写的Hello
随便写点:

<html>
<body>
<h1>Hi,我的第一个Rails程序 </h1>
</body>
</html>

保存好后访问 http://127.0.0.1:3000/Helloworld/hello 其中Helloworld是控制器名,后面的hello是页面模板文件名(大小写注意)
如果无法访问,后台报错RoutingError (No route matches “/Helloworld/hello”) 这时候需要修改/config/routes.rb去掉最后的match ‘:controller(/:action(/:id(.:format)))’的注释,重启应用即可
如果Template is missing 可能是url最后的模板文件名写错了,要对应到*.rhtml

Leave a comment

0 Comments.

Leave a Reply

( Ctrl + Enter )