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])
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
def create
@user = Person.new(params[:person])
end
and our form looked like
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.
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:
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.