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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值