Identify GET and POST parameters in Ruby on Rails

前端 未结 11 766
我在风中等你
我在风中等你 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:38

    You don't need to know that level of detail in the controller. Your routes and forms will cause appropriate items to be added to the params hash. Then in the controller you just access say params[:foo] to get the foo parameter and do whatever you need to with it.

    The mapping between GET and POST (and PUT and DELETE) and controller actions is set up in config/routes.rb in most modern Rails code.

    0 讨论(0)
  • 2020-12-08 14:39
    if request.query_parameters().to_a.empty?
    
    0 讨论(0)
  • 2020-12-08 14:40

    I think what you want to do isn't very "Rails", if you know what I mean. Your GET requests should be idempotent - you should be able to issue the same GET request many times and get the same result each time.

    0 讨论(0)
  • 2020-12-08 14:42

    There is a difference between GET and POST params. A POST HTTP request can still have GET params.

    GET parameters are URL query parameters.

    POST parameters are parameters in the body of the HTTP request.

    you can access these separately from the request.GET and request.POST hashes.

    0 讨论(0)
  • 2020-12-08 14:45

    I don't know of any convenience methods in Rails for this, but you can access the querystring directly to parse out parameters that are set there. Something like the following:

    request.query_string.split(/&/).inject({}) do |hash, setting|
      key, val = setting.split(/=/)
      hash[key.to_sym] = val
      hash
    end
    
    0 讨论(0)
  • 2020-12-08 14:45

    You can do it using:

    request.POST

    and

    request.GET

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