如上圖.Controller 的工作便是接收Routing請求,去 Model 讀或寫資料,再使用 View 來產生出 HTML
Controller命名慣例的最後一個單字是以複數形式結尾(但也有例外,比如 ApplicationController)
舉例來說:ClientsController 優於 ClientController,SiteAdminsController 優於SitesAdminsController.
而命名需注意的是,Model的命名慣例是以單數形式命名而Controller是複數
Methods and Actions
當應用程式收到請求時,Rails的Router會決定這要交給Controller的那一個Action來執行
class ClientsController < ApplicationController def new end end
例如,使用者想要在/clients/new 新建一位 client,則可在new這個action進行以下設定,則new.html.erb 頁面的資料會傳遞給Controller的new
def new @client = Client.new end
Parameters
在Controller中接收數據的方式有兩種
第一種稱為query string parameters,是接在URL後面發送的參數,通常是透過HTTP GET方式傳遞
另一種為POST data。通常來自使用者在表單所填寫的資料,會稱為POST data是因為僅能透過HTTP POST 請求的方式來傳遞
用以下例子來說
status為Query String,透過http get的方式傳入,路徑大概為/clients?status=activated
而client為POST data,透過HTTP POST 請求的方式來傳遞
class ClientsController < ApplicationController def index if params[:status] == "activated" @clients = Client.activated else @clients = Client.inactivated end end def create @client = Client.new(params[:client]) if @client.save redirect_to @client else render "new" end end end
Hash and Array Parameters
params Hash可不僅僅是一維的,可在其中再多包一個array或是hash.
若想以陣列形式來傳遞參數,在鍵的名稱後方附加[]即可,如下所示
GET /clients?ids[]=1&ids[]=2&ids[]=3
則在Controller中
puts params[:ids] => ["1", "2", "3"]
這裏要注意參數的值永遠是字串類型。Rails不會轉換類型。
接下來說明一個二維的例子,以下面這表單來說,括號中為鍵值名稱
<form accept-charset="UTF-8" action="/clients" method="post"> <input type="text" name="client[name]" value="Acme" /> <input type="text" name="client[phone]" value="12345" /> <input type="text" name="client[address][postcode]" value="12345" /> <input type="text" name="client[address][city]" value="Carrot City" /> </form>
表單送出後params[:client]的值如下
{ "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }`
其中以下部分即為二維的部分
{ "postcode" => "12345", "city" => "Carrot City" }
JSON parameters
在處理web service時,處理JSON格式的參數優於其他種參數,當接收到的格式為json時Rails會將收到的 JSON參數轉換好後(ruby的hash格式)存至params裡。用起來與一般Hash相同。
若是接收到的json內容為
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
則取得的參數會是
params[:company] => { "name" => "acme", "address" => "123 Carrot Street" }