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

ubuntu下安装ruby on rails

看完《黑客与画家》有了许多感悟和想法,找时间要整理一下,其中之一就是想看一下ruby,为将来做准备。

安装脚本:
sudo apt-get install build-essential gcc g++ libssl0.9.8 libssl0.9.8-dbg libssl-dev build-essential
sudo apt-get install ruby
sudo apt-get install libzlib-ruby rdoc ri irb ruby1.8-dev
sudo apt-get install libzlib-ruby
sudo apt-get install rubygems
sudo gem install rails -y
sudo gem install rails –include-dependencies
sudo gem install mongrel -y
sudo gem install mongrel_cluster –include-dependencies
sudo apt-get install libopenssl-ruby
sudo apt-get install libgd-ruby1.8 libyaml-ruby libzlib-ruby
sudo apt-get install imagemagick
sudo apt-get install libmagick9-dev ruby1.8-dev
sudo gem install RMagick -y
sudo apt-get install libsqlite3-dev build-essential
sudo gem install sqlite3-ruby

安装完成后
rails new helloworlddemo
ruby script/rails server

http://localhost:3000/

就跑起来了~