可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Is there a neat way in rails to get a hash of the params without the default ones of 'action' and 'controller'? Essentially without any param that wasn't added by me.
I've settled for:
parm = params.clone parm.delete('action') parm.delete('controller');
But wondering if there is a neater way to do this?
回答1:
回答2:
If you are working in a controller, you should also have access to the request object.
To make a long story short, rails and rack groom incoming GET/POST requests (form, xml, json) and pull out the parameters so that developers have a consistent way of accessing them.
ActionDispatch exposes the consolidated list of params via:
# ActionPack 3.1.8 - action_dispatch/http/parameters.rb # Returns both GET and POST \parameters in a single hash. def parameters @env["action_dispatch.request.parameters"] ||= begin params = request_parameters.merge(query_parameters) params.merge!(path_parameters) encode_params(params).with_indifferent_access end end alias :params :parameters
As you can see, params is an alias for the parameters method which is a merged hash of two sub-hashes: request_parameters and path_parameters.
In your case, you don't want the path_parameters. Rather than using except, which forces you to know which path parameters you want to exclude, you can access your data via: request.request_parameters.
A word of caution: You may be better off using :except if you require the hash to be encoded and keys to be accessed as either strings or symbols. The last line of the parameters method handles that for you:
encode_params(params).with_indifferent_access
An alternative approach using except and ensuring that you are removing all rails non-request parameters:
path_params = request.path_parameters params.except(*path_params.keys)
回答3:
request.path_parameters
returns path_parameters
request.query_parameters
returns request_parameters
You are looking for the latter.
回答4:
use
request.request_parameters
it excludes the path_parameters (controller and action)
回答5:
I use
request.request_parameters.except(controller_name.singularize)
This strips out the nested object that is named after the active controller. For example with the following controller:
Class SessionController > ActionController::Base def create User.find_by(params[:email]).login(password: params[:password]) puts request.request_parameters end end
With the following posted value from a web form:
{email: 'test@example.com', password: 'password123'}
The console output will be:
{"email"=>"test@example.com", "password"=>"password123", "session"=>{"email"=>"test@example.com", "password"=>"password123"}}
The above lines of code avoid this.