How I Understand Rails Params
Firstly, params is really not a thing!
Params is a hash like Rails object created by ActionController::Parameters. The source code of module Parameters is here. Params is just a fussy way that rails is trying to make our life easier (yet seems it’s making some new comers struggled..)
Information is passed around as http requests and server response. Every request would have a header, a body and url. Params can be passed by the url and body. One thing to keep in mind is GET request does not have a body.
Params is really just a fancy way to strip the useless information and format the useful ones. For example, in a get request as below.
The only params that will be extracted is going to be { :id => 3 }. Since a get request do not have a body, url is the only way to pass params to the server.
However, in post/patch/put/delete requests, information can be passed through the request body. That’s how form information are sent to the server. Consider this request
By just looking at the url is not going to show us a full picture. In the html form, we will have title and body. So the params will look something like this
{ :post => { :title => ‘A blog post’, :body => ‘a blog post body’ } }
Indeed, the params will also contain information of the authenticity_token if you have forgery_protection set as true.
All the information in the params hash are just extracted from the gabligoob from the http request. You can find the original request by inspecting elements on your browser. It might look some sort of nonsense to you though.
What the params keys and values are is entirely set by us. Consider this simple form below.
<form action=<%= posts_url %> method=“post”>
<input type=“text” name=“post[title]”>
<input type=“text” name=“post[body]”>
<input type=“submit”>
</form>
The bolded part is where we specify the keys of the params, which can totally be customized. Whatever you name it, it will show up as the key in the params.
It’s very easy to lose track of what params is set. The easiest way to find out is not remembering them. We have some great gems like byebug, binding_or_caller that we can use to check params at any time. When not sure, just fire up the console and check it out. That’s all I got for today.