[Rails] Rails 學習筆記(1)

安裝 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

  1. class SayController < ApplicationController
  2.   def say_hello
  3.   end
  4. 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 用來產生時間…

  1. class SayController < ApplicationController
  2.   def say_hello
  3.     @time = Time.now
  4.   end
  5. end

則在 say_hello.rhtml 要顯示的話只要把它包進去就好了…

  1. <html>
  2.   <body>Hello World,<%= @time %></body>
  3. </html>

如果要指定其他action 使用現有的views 只要用render() , 假設我們現在定義一個action 叫next_hour 來顯示現在時間加1小時候的時間~ 在他的function 裡面用 render() 方法即可 , say controller完整的內容如下…

  1. class SayController < ApplicationController
  2.   def say_hello
  3.     @time = Time.now
  4.   end
  5.   def next_hour
  6.     @time = Time.now + 1.hour
  7.     render(:action=> :say_hello)
  8.   end
  9. end

0個對 “[Rails] Rails 學習筆記(1)” 的回應


  • 無評論

留下回覆