How Params Works in Rails

Posted by Flatiron School  /  November 19, 2012

The following is a guest post by Akiva Leeder and originally appeared on his blog. Akiva is currently a student at 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 parameters 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

def show
@person = Person.find(params[:name])

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

def create
@user =[:person])

and our form looked like

Blog post image: tumblr_mdqpewhhie1rtan47.png

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 = 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.

class Playlist < ActiveRecord::Base
attr_accessible :name, :songs_attributes

has_many :songs
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:

Blog post image: tumblr_mdqpf8wNB81rtan47.png

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

params["playlist"]["song_attributes"][2]["track"] = "Beautiful Day"

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

Interested in learning more about coding?

Learn for free with our introductory coding courses.

Flatiron also offers our full-time software engineering course aimed at helping you start a brand new career as a professional developer.