Params - A Basic Explanation On How They Work.

mendel margolis
3 min readJan 27, 2021

If you have ever created a rails application you encountered params and at first they seem very complicating, so we will go through a step by step as to what params are doing under the hood .

Now that we are using rails, there is one major difference that we didn’t have while using apps with active-record, and that is we interact with the app via the web, now because the app is not in our console we don’t manually input all of the arguments we need to create or edit different instances, instead, the arguments are now provided via the web, so we need a way to access it to create, or edit different instances saved in our database.

This is where params come in, params save all data that comes dynamically through the web and saves it in a hash.

 "user"=>{"name"=>"mendel"}, "commit"=>"create user", "controller"=>"users", "action"=>"create"} permitted: false

How does this work?

This is the basics of how Params work, the ‘key’ is how we save the information coming through the web, for example, if I am rendering a form to the website, in every field of the form where the user is inputting information, I create a key and then the incoming data is stored in that key, and every time I would need to access that data I just call “params[: key] “ and that retrieves the data the user put in.

<%=u.text_field :name  %>

This ‘: name’ is now the key that will store any information coming from the web in the name field of that form, and to access it we write

@user = User.create(params[:name])

Now the server will create a new instance of a user with the name provided by the user through the form on the website.

So the user on the website will see a plain form asking for his name, and on the server, we will save it in the key we place in that text_field

Now another way that params work is in a dynamic URL, a dynamic URL just means a URL with an argument, to illustrate, below is depicted a static URL

get 'pictures'

And this is a dynamic URL

get 'pictures/:id'

Now all rails see is that there is an argument given, not what the argument says, so any argument you write in your browser, even if it does not match ‘:id’ the server will direct you to the controller outlined in the dynamic URL, that's why if you are writing a ‘new’ path you should write it before the ‘show’ path because the server will match it to the first dynamic route it sees, now the point of writing ‘: id’ is that this argument will be the key for params.

let's say you write in your URL

pictures/1

saying you want the picture with the id of one, the params will save that argument of one and you can call on it later like so,

@picture.find(params[:id])

and then we can render the picture with the id of one.

I know this does not cover everything about params and how they work, but hopefully, this will better your understanding of why we need them and what they are doing.

--

--