开发者

Getting the rails 'params' without the defaults?

Is there a neat way in rails to get a hash of the params without the defau开发者_如何学Golt 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?


You could use except:

params.except(:action, :controller)

http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Hash/Except.html


request.path_parameters

returns path_parameters

request.query_parameters

returns request_parameters

You are looking for the latter.


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)


use

request.request_parameters

it excludes the path_parameters (controller and action)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜