Identify GET and POST parameters in Ruby on Rails - ruby-on-rails

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?

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

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

You can do it using:
request.POST
and
request.GET

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.

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.

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

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.

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.

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.

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.

if request.query_parameters().to_a.empty?

Related

How does the params method work?

I have been trying to figure out how the params method works and I'm a bit stuck on the process.
For example, if a user clicks on a certain blog post in the index page, I guess that the link_to method calls the Post controller and the show action along with its block #post = Post.find(params[:id]) and then goes to the database to find the post and the view displays it.
So my missing link seems to be when is the post id passed into the params method?
Because the others already explained about params, I'm just going to answer directly a question of yours:
when is the post id passed into the params method
I think it's best explained with an example; see below:
say that you clicked a link:
/posts/1/?param1=somevalue1&param2=somevalue2
The Rails server receives this request that a client wants to view this GET /posts/1/?param1=somevalue1&param2=somevalue2 address.
To determine how the Rails server will respond, the server will first go to your routes.rb and find the matching controller-action that will handle this request:
# let's say your routes.rb contain this line
# resources :posts
# resources :posts above actually contains MANY routes. One of them is below
# For sake of example, I commented above code, and I only want you to focus on this route:
get '/posts/:id', to: 'posts#show'
From above notice that there is this :id, Rails will automatically set params[:id] to the value of this :id. This is the answer to your question where params[:id] comes from.
It doesn't have to be :id; you can name it whatever you want. You can even have multiple URL params like so (just an example):
get /users/:user_id/posts/:id which will automatically set the value on params[:user_id] and params[:id] respectively.
In addition to this URL params like :id, Rails also injects values to params[:controller] and params[:action] automatically from the routes. Say from the example above, get '/posts/:id', to: 'posts#show', this will set params[:controller] to 'posts', and params[:action] to 'show'.
params values also comes from other sources like the "Query string" as described by Mayur, and also comes from the body of the request, like when you submit a form (the form values are set within the body part of the request) and like when you have JSON requests, which all of these are automatically parsed by Rails for your convenience, so you could just simply access params and get the values as you need them.
Params are hashes in ruby with Indifferent access which means,
hsh = {"a" => 1, "b" => 2}
Consider this hsh as params returned from a POST request from browser, it's a key value pair with keys as string. Since it's a params so the values can be accessed as
hsh["a"]
=> 1
hsh [:a]
=> 1
params are formed on the client where the interface load, consider a form which has a submit button. When you press submit, the data filled in form or any hidden textboxes are formed into a hash and passed across the request. This when received on server end will be called as params or request params.
For Get requests: data send across the url will be read as params on backend.
GET: http://www.abx.com?user=admin
params on backend: {"user" => "admin"}
This will be displayed in rails server logs
For Put request: data send across the body will be called params.
PUT: http://www.abx.com
data: {"user" => "admin"} Client side
params on backend: {"user" => "admin"}
This will be displayed in rails server logs
How does the params method work?
The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the URL. For example, if a user's browser requested
http://www.example.com/?post=1&comment=demo
then params[:post] would be "1" and params[:comment] would be "demo".
In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes or array or strings inside.
It might look like this:
{"post"=>"1", "comment"=>"demo"}
Link to Rails Guides on params: guides

What is the right Rails route for passing in a different parameter than id, to return a JSON User object? Controller method provided

EDIT: This is Rails 4
Rails code in the users_controller.rb file
def showobjectdata
#users = User.all
#user = User.find_by(:username => params[:username])
render :json => #user
end
I have been trying lots of routes, but (add the "localhost" part to the beginning of this URL) /users/showobjectdata/existingusername in my browser
returns null.
Please Note: I am able to render JSON data about all users or a specific user, if I look up the user some other way than passing in a parameter which is not an id in the browser's URL field. Like in the controller method I can specifically look up a user by a specific email address. And users/show/:id renders the JSON user data of that id, because I have defined the show controller method to render JSON user data (for now).
Here is an example of a route I tried in my routes.rb file:
match 'users/showobjectdata/:username', to: 'users#showobjectdata', via: [:get, :post]
I tried various combinations with plain GET, plain POST, nested parentheses, etc. I always get null except for plain POST which doesn't work.
Try this
match 'users/showobjectdata/:username', to: 'users#showobjectdata', via: [:get, :post], param: 'username'
This is the right answer.
Basically, my username parameter (firstname.lastname) was not being passed as a full string. It is was being passed as firstname instead of firstname.lastname, with the Rails application considering "." to be where the format parameter started ('lastname' was considered a format input in the passed in parameters). I saw these passed in parameters appear in my browser ironically only when I got another error trying something new (basically my application was not responding to 'respond_to |format|' in the 'showobjectdata' method when I tried it pretty randomly - this of course led to these parameters showing up at the bottom of the screen and the googling of a solution. Yes after getting this insight on the parameters, I skipped the respond_to way and once again just rendered the json user object directly as before, without differentiating between the HTML and JSON formats).
So, basically this is the right route that worked for me:
match 'users/showobjectdata/:username', to: 'users#showobjectdata', via: [:get, :post], :constraints => { :username => /[^\/]+/ }
The controller method as originally posted is fine!
Source for the ":constraints =>" part:
Why do routes with a dot in a parameter fail to match?

How to tell whether your controller action was given parameters?

I am trying to determine whether my controller action was called with parameters or not, without hardcoding which parameters can be added on.
So I want to distinguish between
/my_controller
and
/my_controller?q=1
I know that I could look inside the params hash, and check whether it ONLY contains :controller and :action keys. This seems ugly to me, is there a smarter way of doing this check?
There is one direct solution:
request.env["QUERY_STRING"] # => "q=1"
Or with Ruby 1.9.2:
request.env.QUERY_STRING # => "q=1"
For GET request you can use request.query_parameters method. There is also request.request_parameters for POST requests.
Results for request.query_parameters.inspect are:
for '/my_controller' => '{}'
for '/my_controller?q=1' => {"q"=>"1"}

Ruby On Rails REST: Customize URL pattern for POST request

I am new to Ruby On Rails and need some help implementing REST protocol.
Whenever you do a POST on REST you get a URL back e.g. http://my-site.com/id/1
I need a customized response in URL format which I have given in example above.
Lets say I am doing a post on parameter <main-id>123</main-id>
The customized response I am looking for is http://my-site.com/123/id/1
What I want to implement is, whatever parameter ID I passed during a post I want that as a part of the response URL output.
Thanks for any help in advance.
You can specify any URL in your controller, e.g.:
def create
... # create record here
redirect_to "/#{params[:main_id]}/id/#{#record.id}"
end
Of course, you'll probably want to use the url helper based on your defined route:
def create
... # create record here
redirect_to my_oddball_path(#record, :main_id => 123)
end
Provided you are using Rails 3, you could just add this route with the proper controller/action
match ':main_id/id/:id', :controller => 'foo', :action => "bar", :via => :post, :as => main_id
Then you can just with the helper main_id_path(main_id, #record)

how to require and check url parameters in rails 3

Is there a way in your routes file to check and validate URL parameters. I am NOT talking about restful '/controller/action/:id' params, but 'controller/action?param1=x&param2=y&param3=z'. I need to be able to validate each parameter and require them.
Yes, you can. For example to check that param1 exists and is not blank you would do the following:
match 'c/action' => 'c#action', :constraints => lambda{ |req| !req.params[:param1].blank? }
You can also scope these constraints to apply them to multiple routes:
scope :constraints => lambda{ |req| !req.params[:param1].blank? } do
match 'controller/action1' => 'controller#action1'
match 'controller/action2' => 'controller#action2'
end
The problem with constraints approach outlined by Pan Thomakos is that it will prevent the url with invalid set of parameters from ever reaching your codebase and you being able to respond to the user in a meaningful manner(the user will see page not found error I believe).
If that satisfies your requirement, thats fine, but a more user-friendly way would be to move parameter validation into the corresponding controller where in your action method you would go through the set of params this action method has received and if any of the required are missing, you would construct a meaningull message and error it back to the user via a:notice

Resources