Rails - Controllercheatsheet
贡献者:BAI
Rails - Controller
常见用法
RUBYredirect_to root_urlredirect_to root_url, notice: "Good."
特殊的 Hash
RUBYsession[:user_id] = nilflash[:notice] = "Hello" # 下一次请求设置 flash 的内容flash.keep # 保存 flash 的值flash.now[:error] = "Boo" # 只在当前的请求生效(下一个请求不生效)cookies[:hello] = "Hi"params[:page]# params 由下面三种参数组成query_parameterspath_parametersrequest_parameters
respond_to
RUBYrespond_to do |format| format.html format.xml { render xml: @users } format.json { render json: @users } format.js # 会被浏览器执行end
default_url_options
RUBY# options 参数是传入给 url_for 的 hashdef default_url_options(options)end
Filter
RUBY# callback 形式before_filter :authenticatebefore_filter :authenticate, except: [:login]before_filter :authenticate, only: [:login]def authenticate redirect_to login_url unless controller.logged_in?end# inline 形式before_filter do |controller| redirect_to login_url unless controller.logged_in?end# 在类中形式before_filter LoginFilterclass LoginFilter def self.filter(controller) ...; endend# Filter 设置例外skip_before_filter :require_login, only: [:new, :create]# 同时 before/after filtersaround_filter :wrap_in_transactiondef wrap_in_transaction(&blk) ActiveRecord::Base.transaction { yield }end
HTTP 基本认证
RUBYbefore_filter :authenticate# HTTP 基本认证def authenticate authenticate_or_request_with_http_basic { |u, p| u == "root" && p == "alpine" }end# Digest 认证:def authenticate_by_digest realm = "Secret3000" users = { "rsc" => Digest::MD5.hexdigest("rsc:#{realm}:passwordhere") } authenticate_or_request_with_http_digest(realm) { |user| users[user] }end# 集成测试def test_access auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass) get "/notes/1.xml", nil, 'HTTP_AUTHORIZATION' => authend# Token 验证is_logged_in = authenticate_with_http_token do |token, options| token == our_secret_tokenendrequest_http_token_authentication unless is_logged_in
Request/Response
RUBYrequest.host #=> "www.example.com"request.domain #=> "www.example.com"request.domain(n=2) #=> "example.com"request.port #=> 80request.protocol #=> "http://"request.query_string #=> "q=duck+tales"request.url #=> "http://www.example.com/search?q=duck+tales"request.fullpath #=> "/search?q=duck+tales"request.headers # 返回 Header hashrequest.format #=> "text/html"request.remote_ip #=> "203.167.220.220"request.local?request.xhr?request.method #=> "POST"request.method_symbol #=> :postrequest.get?request.post?request.put?request.delete?request.head?
response
RUBYresponse.bodyresponse.status #=> 404response.location # 跳转的 locationresponse.content_typeresponse.charsetresponse.headersresponse.headers["Content-Type"] = "application/pdf"
流
RUBYsend_data pdfdata, filename: "foo.pdf", type: "application/pdf"send_file Rails.root.join('public','filename.txt') [filename: '..', type: '..']