rails控制器学习笔记

教程原文 http://guides.rubyonrails.org/action_controller_overview.html
.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

你可能感兴趣的:(Flash,Access,Ruby,Rails,ActiveRecord)