How Params Works in Rails

Flatiron School / 19 November 2012

The following is a guest post by Akiva Leeder and originally appeared on his blog. Akiva is currently a student at The Flatiron School. You can learn more about him here, or follow him on twitter here.

As a Rails beginner, I found it hard to understand what params is all about. Apparently, I am not alone. RailsGuides does a good job of laying out the basics, but going through another example is always helpful.

As you might have guessed, params is an alias for the paramaters method. params comes from ActionController::Base, which is accessed by your application via ApplicationController. Specifically, params refers to the parameters being passed to the controller via a GET or POST request.

In a GET request, params get passed to the controller from the URL in the user’s browser. For example, if our app’s controller looked like

and the user typed in:

then the controller would pass in {:name => “avi”} to the show method, which would set the @person instance variable to the person in the database with the name “avi”.

In a POST request, params will get passed to the controller usually from a form. For example, say our app’s controller looked like

and our form looked like

If the user submitted the form with the name “avi” and the email address “” the controller would pass the hash :person => { :name => “Avi”, :email => “”} to the create method. Here, @person =[:person]) will become @person = “Avi”, email: “”)

Using params gets a bit more complicated when working with nested attributes. Take the example of a playlist app, where a playlist has_many songs and accepts_nested_attributes for songs.

Here, the params for a playlist will be a nested hash and may look like this after adding a few tracks:

Now, if we wanted to access the track name for the U2 song, the params would look like this:

Hopefully these examples help to clarify what is often a tricky concept for beginner rails programmers.

How to Close a Git Pull Request Previous Post Ruby Structs Next Post