rails控制器學習筆記

教程原文[url]http://guides.rubyonrails.org/action_controller_overview.html[/url]
.Array參數
Get /clients?ids[]=1&id[]=2&id[]=3
params[:ids]=["1", "2", "3"]

.Hash參數

<form 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”}}

.路由參數

map.connect "/clients/:status",
:controller => "clients",
:action => "index",
:foo => "bar"

params[:foo] => "bar"


.Session
Session存儲策略
1、CookieStore:在客戶端存儲任何東西
2、DRBStore:在DRb服務器上存儲數據
3、MemCacheStore:在MemCacheStore上存儲數據
4、ActiveRecordStore:在數據裏存儲數據

.Flash
flash是一種特殊的Session,僅可在下一次請求中訪問,且在下一次請求完成後清除。
如果你想繼續保持flash的值到下一次,flash.keep

讓當前請求訪問可flash,flash.now

class ClientsController < ApplicationController
def create
@client = Client.new(params[:client])
if @client.save # ...
else
flash.now[:error] = "Could not save client"
render :action => "new"
end
end
end


.Cookie

#設置
cookies[:commenter_name] = @comment.name
#刪除項
cookies.delete(:commenter_name)
#注意設置cookies[:commenter_name] = nil並不會刪除cookies[:commenter_name]


.Filters

class ApplicationController < ActionController::Base
before_filter :require_login

private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end

# The logged_in? method simply returns true if the user is logged
# in and false otherwise. It does this by "booleanizing" the
# current_user method we created previously using a double ! operator.
# Note that this is not common in Ruby and is discouraged unless you
# really mean to convert something into true or false.
def logged_in?
!!current_user
end
end

跳過filter

class LoginsController < ApplicationController
skip_before_filter :require_login, :only => [:new, :create]
end


after_filter:action調用之後執行
around_filter:action調用前後都執行

.參數檢查

class LoginsController < ApplicationController
#所有action驗證參數
verify :params => [:username, :password],
:render => {:action => "new"}, #檢驗錯誤時渲染action
:add_flash => {
:error => "Username and password required to login in"
}
#如果僅是create要驗證,開啓下兩行
#,
#:only => :create

def create
@user = User.authenticate(params[:username], params[:password])
if @user
flash[:notice] = "You're logged in"
redirect_to root_url
else
render :action => "new"
end
end
end


.請求保護

.Request和Response對象
自定義header

response.headers["Content-Type"] = "application/pdf"


.HTTP認證
Basic Authentication基本認證
Digest Authentication摘要式身份驗證
Digest Authentication可以避免以明文傳輸數據

class AdminController < ApplicationController
USERS = { "lifo" => "world" }

before_filter :authenticate

private
def authenticate
authenticate_or_require_with_http_digest do |username|
USERS[username]
end
end
end

返回false或nil會中斷認證

.Streaming和文件下載
生成pdf

require "prawn"
class ClientsController < ApplicationController
# Generates a PDF document with information on the client and
# returns it. The user will get the PDF as a file download.
def download_pdf
client = Client.find(params[:id])
send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
end

private
def generate_pdf(client)
Prawn::Document.new do
text client.name, :align => :center
text "Address: #{client.address}"
text "Email: #{client.email}"
end.render
end

end


下載服務器已有的文件

class ClientsController < ApplicationController
# Stream a file that has already been generated and stored on disk.
def download_pdf client = Client.find(params[:id])
send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf",
:filename => "#{client.name}.pdf",
:type => "application/pdf")
end
end


RESTful下載

class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])

respond_to do |format|
format.html
format.pdf { render :pdf => generate_pdf(@client) }
end
end
end


添加下面的代碼到config/initializers/mime_types.rb

Miem::Type.register "application/pdf", :pdf


url:GET /clients/1.pdf


日誌過濾
避免key包含password的參數記錄到log

class ApplicationController < ActionController::Base
filter_parameter_logging :password
end



錯誤處理

rescue_from
處理記錄未找到錯誤

class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound,
:with => :record_not_found private
def record_not_found
render :text => "404 Not Found",
:status => 404
end
end

處理未通過驗證錯誤

class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, :with => :user_not_authorized

private
def user_not_authorized
flash[:error] = "You don't have access to this section."
redirect_to :back
end
end

class ClientsController < ApplicationController
# Check that the user has the right authorization to access clients.
before_filter :check_authorization

# Note how the actions don't have to worry about all the auth stuff.
def edit
@client = Client.find(params[:id])
end

private
# If the user is not authorized, just throw the exception.
def check_authorization
raise User::NotAuthorized unless current_user.admin?
end
end
發佈了24 篇原創文章 · 獲贊 0 · 訪問量 2778
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章