rails中的request

来源:互联网 发布:老马说编程 编辑:程序博客网 时间:2024/05/01 23:39

Request資訊收集

ControllerAction之中,Rails提供了一些方法可以讓你得知此request各種資訊,包括:

  • action_name 目前的Action名稱

  • cookies Cookie 下述

  • headers HTTP標頭

  • params 包含用戶所有傳進來的參數Hash,這是最常使用的資訊

  • request 各種關於此request的詳細資訊

    • request_method
    • method
    • delete?, get?, head?, post?, put?
    • xml_http_request? 或 xhr?
    • url
    • protocol, host, port, path 和 query_string
    • domain
    • host_with_port
    • port_string
    • ssl?
    • remote_ip?
    • path_without_extension, path_without_format_and_extension, format_and_extension, relative_path
    • env
    • accepts
    • format
    • mime_type
    • content_type
    • headers
    • body
    • content_length
  • response 代表要回傳的內容,會由Rails設定好。通常你會用到的時機是你想加特別的Response Header

  • session Session下述

正確的說,params這個HashActiveSupport::HashWithIndifferentAccess物件,而不是普通的Hash而已。Ruby內建的Hash,用Symbolhash[:foo]和用字串的hash["foo"]是不一樣的,這在混用的時候常常搞錯而取不到值,算是常見的臭蟲來源。Rails在這裡使用的ActiveSupport::HashWithIndifferentAccess物件,無論鍵是Symbol或字串,都指涉相同的值,減少麻煩。