hero-background-image-header

How Params Works in Rails

By Flatiron SchoolNovember 19, 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 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

1
2
3
def show
  @person = Person.find(params[:name])
end

and the user typed in: http://example.com/person/avi

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

1
2
3
def create
  @user = Person.new(params[:person])
end

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 “avi@example.com” the controller would pass the hash :person => { :name => “Avi”, :email => “avi@example.com”} to the create method. Here, @person = Person.new(params) will become @person = Person.new(name: “Avi”, email: “avi@example.com”)

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.

1
2
3
4
5
6
class Playlist < ActiveRecord::Base
  attr_accessible :name, :songs_attributes

  has_many :songs
  accepts_nested_attributes_for :songs
end

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:

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

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

Headshot of Flatiron School

Flatiron School

Blog Post Author

All Articles by Flatiron School