安裝 Rails 還有相依性套件,到console
gem install rails –include-dependencies
建立新 project
rails demo
啟動內建Webrick 伺服器
ruby script\server
預設prot 是 3000 , 所已啟動 Webrick 後,可以到 http://127.0.0.1:3000/ 看看
What’s MVC ?
M = Model , 儲存與處理資料
V = View , 產生頁面視圖(in /app/views/ )
C = Conteoller , 控制行為action , 建立與view的關係(in /app/controllers/ )
建立一個新的 controller (ex:say)
ruby script\generate controller say
say controller (/app/controllers/say_controller.rb)裡面建立一個 say_hello action
- class SayController < ApplicationController
- def say_hello
- end
- end
而 say_hello 這個 action 所對應到的 view 是 /app/views/say/say_hello.rhtml(自行建立)
若action 找不到相對應的 views , 會顯示下列錯誤訊息
Template is missing
Missing template say/say_hello.html.erb in view path x:/xxx/demo/app/views
在 *.rhtml 裡面可以用 <% %> 包住 ruby 程式碼… 例如在 action 裡面定義區域變數@time 用來產生時間…
- class SayController < ApplicationController
- def say_hello
- @time = Time.now
- end
- end
則在 say_hello.rhtml 要顯示的話只要把它包進去就好了…
- <html>
- <body>Hello World,<%= @time %></body>
- </html>
如果要指定其他action 使用現有的views 只要用render() , 假設我們現在定義一個action 叫next_hour 來顯示現在時間加1小時候的時間~ 在他的function 裡面用 render() 方法即可 , say controller完整的內容如下…
- class SayController < ApplicationController
- def say_hello
- @time = Time.now
- end
- def next_hour
- @time = Time.now + 1.hour
- render(:action=> :say_hello)
- end
- end
0個對 “[Rails] Rails 學習筆記(1)” 的回應