Identify GET and POST parameters in Ruby on Rails

前端 未结 11 767
我在风中等你
我在风中等你 2020-12-08 14:16

What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?<

相关标签:
11条回答
  • 2020-12-08 14:50

    You can use the request.get? and request.post? methods to distinguish between HTTP Gets and Posts.

    • See http://api.rubyonrails.org/classes/ActionDispatch/Request.html
    0 讨论(0)
  • 2020-12-08 14:52

    request.get? will return boolean true if it is GET method,

    request.post? will return boolean true if it is POST method,

    0 讨论(0)
  • 2020-12-08 15:00

    I think what Jesse Reiss is talking about is a situation where in your routes.rb file you have

    post 'ctrllr/:a/:b' => 'ctrllr#an_action'
    

    and you POST to "/ctrllr/foo/bar?a=not_foo" POST values {'a' => 'still_not_foo'}, you will have three different values of 'a': 'foo', 'not_foo', and 'still_not_foo'

    'params' in the controller will have 'a' set to 'foo'. To find 'a' set to 'not_foo' and 'still_not_foo', you need to examine request.GET and request.POST

    I wrote a gem which distinguishes between these different key=>value pairs at https://github.com/pdxrod/routesfordummies.

    0 讨论(0)
  • 2020-12-08 15:01

    If you want to check the type of request in order to prevent doing anything when the wrong method is used, be aware that you can also specify it in your routes.rb file:

    map.connect '/posts/:post_id', :controller => 'posts', :action => 'update', :conditions => {:method => :post} 
    

    or

    map.resources :posts, :conditions => {:method => :post} 
    

    Your PostsController's update method will now only be called when you effectively had a post. Check out the doc for resources.

    0 讨论(0)
  • 2020-12-08 15:02

    There are three very-lightly-documented hash accessors on the request object for this:

    • request.query_parameters - sent as part of the query string, i.e. after a ?
    • request.path_parameters - decoded from the URL via routing, i.e. controller, action, id
    • request.request_parameters - All params, including above as well as any sent as part of the POST body

    You can use Hash#reject to get to the POST-only params as needed.

    Source: http://guides.rubyonrails.org/v2.3.8/action_controller_overview.html section 9.1.1

    I looked in an old Rails 1.2.6 app and these accessors existed back then as well.

    0 讨论(0)
提交回复
热议问题