Learning to code at Flatiron School

How Params Works in Rails

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

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

and the user typed in:

1
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

1
2
3
4
5
<%= form_for(@person) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :email %>
  <%= f.text_field :email %>

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[:person]) 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:

1
2
3
4
5
6
7
params = { :playlist => {
 :name => 'pop' , :song_attributes => [
  { :artist => 'Michael Jackson', :track => 'Thriller'},
  { :artist => 'Stevie Wonder' , :track => 'Superstition'},
  { :artist => 'U2', :track => 'Beautiful Day'}
  ]
}}

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.