Rails: Action Controller
2017-05-13 本文已影响37人
bookinstock_
Guide Targets:
- How to follow the flow of a request through a controller?
- routes -> controller#action -> model -> c -> view -> c -> client
- How to restrict parameters passed to your controller?
- use strong parameters! with
require
andpermit
- use strong parameters! with
- How and why to store data in the session or cookies?
- use
session
andcookies
instances, make conversation :P
- use
- How to work with filters to execute code during request processing?
- use
before_action
to halt flow when something bad happen..
- use
- How to use Action Controller's built-in HTTP authentication.
- basic auth and digest auth, not try.
- How to stream data directly to the users's browser?
- use
send_data
andsend_file
better restful way.
- use
- How to filter sensitive parameters so they do not appear in app's log?
- some config like
config.filter_parameters
- some config like
- How to deal with exceptions that may be raised during request processing?
- use
rescue_from
to handle specified exceptions.
- use
My Notes
ActionController
- get
controller
andaction
name from - params
params[:controller] params[:action]
- methods
controller_name, action_name
Default URL params
default_url_options
Request
request.class => ActionDispatch::Request
- methods1:
host, domain(n), port, protocol, url, query_string
- methods2:
method, get?, post?, put?, patch?, delete?, head?
- methods3:
format, headers, body, remote_ip
- parameters1:
path_parameters
from routing - parameters2:
query_parameters
from query string - parameters3:
request_parameters
from post body
Response
response.class => ActionDispatch::Response
- methods:
headers, body, location, content_type, charset
Strong Parameters
-
require
to specify required params -
permit
to specify permit params (danger to usepermit!
) params.require(:foo).permit(:a, :b, :c)
params.fetch(:bar, {}).permit(:a, :b, :c)
Session
ActionDispatch::Session::CookieStore
ActionDispatch::Session::CacheStore
- use a cookie to store uniq id for each session
- change secret will invalid all CookieStore session.
session.class => ActionDispatch::Request::Session
session[:user_id] = user.id # login
session[:user_id] = nil # logout
reset_session
Flash
flash.class => ActionDispatch::Flash::FlashHash
redirect path, notice: "msg"
redirect path, alert: "msg"
redirect path, flash: { foo: 'bar' }
-
flash.keep
keep to next request -
flash.now
render right now
Cookie
cookies.class => ActionDispatch::Cookies::CookieJar
cookies.delete(:key)
Hooks
before_action
skip_before_action
after_action
round_action
Request Forgery Protection
from_authenticity_token
Streaming and File Downloading
send_data
send_file
- resourceful render