Category Archives: Code Academy

Code Academy Week 6 Notes

product has many reviews
There is a proxy for the data – it is a subclass of Array

What is there is no product with that ID?
The “find” method will raise an exception (actually params[:product_id] is nil)
How to make it more forgiving

the find_by_* methods (aka dynamic finders) are more forgiving
You could even get rid of if

How to hide the product pull down in the review form?
Hidden form field
In _form.html.erb for review:

Why do we need an equal sign for if it’s a hidden field?

It still needs to be emitted to the HTML
In Rails, we have 2 methods: present? and blank?
blank? is like nil?
if a string is ”  “, that is not nil, but it is blank
present? is the opposite of blank?
Why have both? Just negate one of them.
!a.blank? is “not the Ruby way” according to Jeff

Matz does not like minimal interface. Sometimes map will feel right, and sometimes collect will.

map is an iterator, like each

map wants a return value from each iteration of the block

<% if @review.product.present? %>
could also be
<% if @review.product %>

show.html.erb for reviews has this at the top:

This method will emit what ever is in the :notice key in the redirect from your controller
This will only live long enough to be redirected
This is called a flash message in Rails
it is a hash
the “flash hash”
You could also set the notice just before the redirect_to

You could make it flash[:zebra]
and call

in the html.erb file

http is stateless, so each request has to provide all the information the next request needs
Putting the query string in the URL has been one way to keep information
User story:
as a user, I want to add several products into a shopping cart
Jeff does it:
Carts and Products
This is many to many
But many carts will want to have products
Make a join model in between
Cart has_many :cartItems
cart_item belongs_to a single :cart
A product will have many cart items
a cart item will belong_to a product
cart_itme will have cart_id and product_id

add has_many :cart_item to product
The file name is Pascal case. In code or console, you use underscores

Jeff says the modelling is the hard part of Rails
In the console, you can do this:

in console, this will reload items from database
or: cart.cart_items.create :product => Product.last will make a new cart in memory only. does not exist on the proxy

Add item to a cart. How to add another item to same cart?
Use cookies
Session data
Each has a name and a value
name/value pair, like a hash in Ruby
Expiration is optional – session by default
cookie data lives in the browser
How to add cookies:

Each cookie is limited to 4K of data
Do not put an ActiveRecord object into a cookie
Cookies are stored on the client machine
deal with session hash in your controllers
It is defined in ApplicationController’s parent
session[:cart_id] =
The session data is encrypted
In the create method for Cart controller:

Put the cart stuff in a partial that everything can see.

Instead of accessing session hash inside view, make a helper method
Use view helpers

Seed file
Seed file will help you pull in test data

Vince did pagination

Checkout: cart becomes an order
Cart partial:

In routes:
resources for :orders
Create an orders controller

Look at guides for sessions and cookies

In grandma example, they used a form_tag, not a form_for since they did not use a model.
form_tag(“/ask”, :method => “get”) do
put form tags here

get ‘ask’ => ‘grandmas#ask’

What we started:

Jeff recommends irb or rails console

Two methods:
a.upcase will check if the string contained in a is uppercase
a.upcase! will change the string to uppercase

Some people used regular expressions

Now going back to the shopping cart.
New models: Order, OrderItem

reset_session will reset the whole session
how to just get rid of cart?

Cycle through the cart creating order items, and call afterwards. Fewer transactions.

New app for users

Do not store passwords as strings. We will go over that later.

You could put this in the seeds.rb:

etc, etc, etc,

To wipe out existing items in database, you could add this at the top of seeds.rb
He added users and items to routes with resources

Signup is easy: Just add user to database
Signin and signout are session management
If they are in database, when they sign in just make a session cookie

We create a sessions controller, inherits from application controller

There will also be a folder for sessions, with a new.html.erb
We use form_tag instead of form_for since we have no model

Now in app layout:
if session[:user_id].present?
Hello, User.find(session[:user_id]).name

In routes:
post “/logout” => ‘sessions#destroy’, :as => :logout
link_to “Sign Out”,
button_to will create a post

Make the password a password_field_tag
To do password confirmation:
add a text field in form: password_confirmation, which you can do even though we are in a form_for
Then in model for User:
validates :password, :confirmation => true

For password security:
add “bcrypt-ruby” to Gemfile, run “bundle install”
To user, add a column called “password_digest” as a string
add line “has_secure_password” to the model

If you make a mistake,

Put line “has_secure_password” into the model
For user form partial:
Remove the password digest field from the form
Put in password and password_confirmation

Create an account and sign in at the same time
In users controller in create

So how do people sign in? We don’t want them to know their digest
In console:

That should work
It will encrypt the input, it will not decrypt the string in the database

Code Academy Week 5 Notes

He went over SQL in Ruby/Rails
Team has many players, Player belongs to Team

User story:
As a user, I want to see a list of products I can buy
A product has a name, color, and price. A product belongs to a single brand.
Prices are always in exact dollar amounts (no cents).
As a user, I want to add a review to a product
A review has a rating from 1-5 and a brief description

new rails app
products and brands
products belong to brand, brand has many products
Generate scaffold for brand and product
go back to index after create

Go over the scaffold
To get the brand in the collection select
Go to the form partial for the product
Only change the number field, not the label field
brand_id is the foreign key

:id is param for Brand.all, :name is the field in the brand. That is what will be displayed
You may not want to always do Brand.all. We will go over that later.
View should not decide what data to show.
Put a variable in the new method in the controller

Now listing the products, we still get the brand ID

Make the description for a form a text field, not string

For rating, we want a list of  to 5

You should still add a validates method in the model
What if you want 1 to 100?
There is a way to do a range

to_a converts it to an array
Make the description box smaller. Go to the form partial
:rows => 5

You can have more than one version

You may see:

That will install it with admin rights
With rvm: never use sudo
It will install latest by default
gem will handle dependencies
railties is the guts/engines of rails
You can call
gem sources
to see where it will look for gems

Vince’s app:
We could edit the Gemfile

Then run

Back to Jeff
How to get words to appear on pull-down



To validate that the rating will be between 1 and 5
Jeff starts with the guides
Jeff used

Test in the Rails console

To support 1 URL: pages/social
One way:

rails new friendBC
cd friendBC

-> Memorize the routes for resources
in routes.rb
get “pages/social”
in app/controllers add a controller: PagesController < ApplicationController
add a method called “social”
add app/views/pages/social.html.erb
get an image, put it in

in assets/global directory
Make the background grey

How to get JSON data?
He put some stuff in his controller

Put result in view file
In hashes, symbols and strings are not interchangeable. Usually they are.
To get the image:
in the view:

Now he is calling @result @channel

Now Jeff is going through it
Agile practices: single responsibility, clear intention, DRY
These are the top 3
Rails cries out to help you do those things
When you download someone else’s code, you may need to run “bundle install”
Jeff moved some of the HTML onto a partial
Then change the variable in partial to one called “channel”
Then in the view call

In the partial, do not use raw “a” and “img” tags

Now add the image:

Now back in view, we call the render three times. What if we pull another channel, we will have to add another line.
So in controller, create an array

In the view:

Now they do not need to be instance variables in the controller
We still have repetition

Then in other method:

This is Ruby skillz

A good pattern to know:
An array of strings. You are transforming the array into another array.

map is like each
Look it up
collect is another good one to look up.

Could be

We saw one-line blocks in scaffolds in index

Look in the dev/tth/shop folder
Now: git and github
Look up “git – the simple guide”

makes a new repository

to checkout a repository
working dir has files, index to stage commits, the head is the last commit
adding and committing

Now it is in the head, but not remote

afterwards, you can just do git push
To add a branch

to reset:

gitk – is a good GUI
Neal making live changes

He is on master branch

git status now tells him he made a change

or just

There is also heroku


Heroku requires postgres

Neal makes a new app

It would be nice to stop an existing rails server
You could also specify a port

It is now live on our local machine

go to
make a new repository

No good

Now put it up to heroku

ssh keys are a pain

They have different stacks. bamboo is the current stack, good for rails up to 3.0. For rails 3.1 use cedar
Now push it to heroku
Update the gem file Gemfile to add postgres

Put sqlite3 in group :development
bundle install
now commit changes to git

Now push to heroku

another command: heroku open
assets, like images, there could be some problems
another command is heroku logs

it’s like an irb for heroku

in file app/config/environments/production.rb

You can go to
Working with Shop app:
Get the average of reviews for a product

Calling It gets rows from our table. It looks like an array, and behave like an array, but it can do more than what an array can do. It returns a proxy class. It is a proxy for the data you want.
So you can say – it makes an SQL statement
You can do a lot of array stuff:,“rating”)
Arrays do not have sum method, but ActiveRecord does have sum method“rating”) it gives us a BigDecimal instance“rating”).to_s

Another association concept
A brand has many products.
A product has many reviews.
A brand has many products throught its products.

The lines must be in that order
Review does not have brand id, but product has brand id, and review has product ID
So you can just do without looping
Users want to see average rating for brand
So in brand show page – put it there for each brand
So to brand index page:


For reviewing the product form, it would be great if it knew which product you were using
No params hash for /reviews/new
Put a placeholder in the route
Put it in URL via ?key=value
Now you have a params hash
In product/show.html.erb

So now you see ?product_id=1 in url for new form
so in controller, look at new action in review controller

so in reviews/new.html.erb
New review for

Next: Leave out the pull-down form. But get product ID
replace collection_select with a hidden field

Code Academy Week 4 Notes

I only seem to have notes for the second day of week 4.

2012-02-02 Notes

Scaffolding notes:
partials: Like a server side include

Look up respond_to method

JSON only:

You could use curl as well.

Try getting a png:

I did not know there was a code 406.

There is a method called responds_with :html, :json, :xml
Not used too often.  That was intended for all actions, but people did not want universal responders.

Scaffold does not provide any security out of the box.

New action also has a block to send json back
526  curl -v “http://localhost:3000/runners/new.json” -H “Accept: application/json”

This could help other developers know what data fields your classes have

The create action has an if block in the respond_to call to handle both a successful and unsuccessful creation.

In Ruby 1.9, you can use a new syntax for hashes

You could also do it like JSON

You can only use the colon for keys if your key is a symbol.
So if you mix key types like in hash i, things get a bit ocnfusing. Your value can be a symbol, but that colon must still be on the left.

Assigment: look at the destroy. What is head :no_content about?

Memorize the RESTful Design chart with the routes, URLs, actions, etc

Let’s look at new and edit
TextMate tip: could go to the drawer. There is another way to get there. Command-T pops up a window, type in the name of your file. You can type something in the middle.
Look at the “new.html.erb” page. Where is the form?
Look at the “edit.html.erb” page. Where is the form?
We see this in each file:

There is a file app/views/runners/_form.html.erb
Partials begin with underscores.
You just use the render method.
You can use instance variables in the partial.

From index.html, you could take this and put it in a partial:

into a file called _list_of_runners.html.erb
and replace it with

It makes the index.html clearer, but clutters up the directory.

Back to associations:
One movie has many actors:

User stories:
As a user, I want to see the list of teams in our softball league.
A team has a company name and a nickname.
As a user, I want to select a team, and see the list of players on the team.
A player has a name and a jersey number.

What about many-to-many?
Actors are in many movies, and movies have many actors.
There is the notion of a “Role” in between Movie and Actor. That joins them together.
Movie <-> Role <-> Actor
Movie has many roles, and an Actor can have many roles
Roles would have id, movie_id and actor_id

    belongs_to :movie

    belongs_to :actor



User <-> Review <-> Landmark

You just generate a model for a role
rails g scaffold Movie title:string year:integer
rails g scaffold Actor name:string
rails g model role movie_id: integer actor_id:integer character:string
Add the has_many and belongs_to statements

IN the console:
the hard way

Another way to create a role

Some stuff on migrations and controller filters
What about the salary for the role?
You cannot put it in the old migration file and re-run that
The timestamps are on there for a reason

You need to create a new migration for the new field
rails generate migration $NAME $FIELD:$TYPE
rails generate migration AddSalaryToRole salary:integer
It might generate the right thing. You would need this:

Then type rake db:migrate to make changes
rake db:version

Controller filters:
In the controller, we do

quite a few times. (This would be better for something that is multiple lines.)
Make a method
def find_the_movie
It might generate the right thing.
You can call that when you need to
But there is still some repetition
If you want to call a method at the beginning of an action or method, that is a before filter
Put this at the top:

So even though destroy action has @movie in the first line, you won’t get an error since you get @movie from the filter
But index method does not get params[:id]. You will get an error
So how to run it only for certain actions

or to exclude some methods

DRY-ing code:
partials in views, pull them in with renders
controllers: use filters to extract common code

You can make your db lookups faster with indexes:

You can put these in a migration
You probably want this for foreign keys

Code Academy Week 3

James Spader

James Spader is the baddest mo-fo evah!

I am a bit late, but here is my summary of week 3.

The lectures were rounding out MVC. We made a model class, a controller class, and some view pages. We then made the necessary methods, views and routes to list all the instances, show one instance, edit an instance, and delete an instance. I have been planning to sit down and whip up an MVC example. I just started it last night. I will do it again tonight.

Then Jeff said that we don’t really need to do that. You can just run the

command. Neal pointed out that most people never learn the long way of doing it, they just learn the short way with scaffolding.  Not even the Hartl tutorial covers the detailed way, which kind of surprises me. The ironic thing is that on one day my pair partner is a guy who was taking a semester off from getting a computer science degree from Michigan State. When we had seen the “long” way of doing MVC in Rails, we were surprised at how easy it was compared to other frameworks.

I also saw my mentor. I wanted to do something with OAuth. I made some progress, but I hit a wall. I think the example that I was using was a bit out of date. Uncle Bob spoke. I got there late, but I was told that I saw the meat of the lecture.

I think I need to start getting more disciplined. I think that the “I have seen this before” phase may be ending for me. This is one of the reasons that I am going over the Pickaxe book. Another reason is that there was a shindig hosted by Braintree. Another student said she heard someone at the event who works at one of the local consulting firms saying that Code Academy should not teach just Rails, but more Ruby, since only learning Rails might not be giving people enough knowledge. This is a second-hand (or even third-hand) account of the event. But I guess there is some skepticism about Code Academy.

I also told another student that he looks like James Spader, and now he probably thinks I am a total jerk.

Image of James Spader taken in 2007, found on Wikipedia

Code Academy Week 3 Notes Post 02

2012-01-26_08.08.55 notes
Web requests: URL, method, format
In the routes.rb file, you can have the same URL, but different methods

If you are having trouble naming controllers, go into the Rails console, call the “pluarlize” or “singularize” methods. This will give you the Rails conventions.

In browsers, when you type something in the address bar it will automatically be an HTTP get request


Rails forms will have hashes and sub-hashes

3 parts to HTTP request: URL, method and format
The R is resources
Stop thinking pages, start thinking resources

1. web request
params hash contains the data
2. Rails App

3. Web response

Forms in Rails
use the form_for method.

So you should see params[:station] with :station as a hash in the hash, and containing a key called :name

In the train station app, we could also do
Station.create params[:station]

How to change things in the database?
We use the HTTP method is PUT
We have to name our URLs in the routes.rb file

The form knows to label button “Update Record”
In the rails console, you can call x.new_record?
Rails can support HTTP put method with a “_method” param with a value of “put”

To list methods well:

y puts it in yaml

TO get rid of it:

New is paired up with create, edit paired up with update conceptually, so pair them in your routes.rb file
In the update method of the controller, we could call @station.update_attributes(params[:station])

It is best to use named routes
If there is a URL with multiple HTTP methods, you only need to name them once
In the controllers, you use

If the path is stations:

But what if you need the ID?

You could also do station_path
that will do the relative path
path gives you less data to the client
Only good if you will be in the same domain
Problem if you have a redirect

If you send an ActiveRecord object to a route in a link_to call, you could just send it @the_station instead of
The ID is the only one you could leave off. Everything else must be specified.

We will have a lot of controllers in a web app.
You will be creating, deleting, updating a lot of stuff
You could just do
resources :stations
There will be a cheat sheet for the routes

A lot of people never learn the long way like we did, they just learn the resources :model
Even Hartl does not go over that, which kind of surprises me.

singular for model, plural for controllers, singular for scaffold
It will make a lot of stuff for you

It creates something for a new station, as well as some edit, destroy, etc


Scaffolding is not intended to be the final application
We will see that scaffolding will not do too much, especially when we have multiple models

Model validations: you will have rules about your models, aka business rules, or domain logic
don’t let a user sign up multiple times with same address, is credit card valid, etc, etc
These rules go in the model

If you change model while in the rails console, you either need to exit or call reload!
Many of the variables will no longer be valid
You could call m.valid? and m.errors (which gives a hash)
or call: m.errors.full_messages
That returns an array

The scaffolding will create error handling as well

Code Academy Week 3 Notes Post 01

This week:
Arrays and blocks
MVC Recipe
CRUD your data
Rails resources
Model Associations

2 skills building: RoR coding and how to think about architecture of application

Arrays and blocks:
Arrays and collections

The times method will let you increment a block variable

Mate: command-control-shift-E will execute code


Better way: Use .each method

MVC Recipe file is on Backpack – look it up and save it

Simple page demo:
display a list of train stations
1. Route definition
2. Controller class
3. Action method

1. Define a route that connects a url path to a controller and an action

2. Write a controller class

Follow conventions: Class is StationsController and file is stations_controller
3. Add an action method that generates your HTML

Do not give your app the same name as one of your controllers
render method in the controller can take a file name, or :text => “Some text”

In response, you can give some HTML or redirect the user

redirect will give a 302 http status code
In controller, either render some HTML or redirect


But we could have nothing in the controller’s index method. Or we could put something in the views folder:

added an array @stations in the stations controller
Put this in the index.html.erb file:

You do not need to make an attr_accessor line in a controller to see it in the corresponding view. You can just use those variables in the view.


For a model:

That was if you are using rvm
If not, you might need to use sudo

Models are singular, controllers are plural

Look at the migration file


We can add columns before we do the migration
Migrations allow you to evolve your database. If you change your tables, add tables, etc

In model class, you start with a line like this:

It will give you attr_accessor methods for the fields. Do not put them in.

To do the migration, do this:

To get  the version of the database.

To delete database:

To drop database and start over fresh

If you get errors, try “bundle exec” in front:

Some logs:


You could do Student.create!
This will throw an exception if something went wrong
We would need begin and rescue, and a rescue handler

So now in stations_controller, you can put the Station objects in a variable:

So put this in index:

He went over RailsGuides
Jeff prefers the Guides

Now let’s do something with one train station – the simplest way possible
Define a route that connects a URL path to a controller and action
In routes.rb:

Add a controller action method

You could also do Station.find_by_id(station_id)
Create an html.erb page for the action in app/views/stations

In controller: If we do find_by_id, we get a nil return value
if we do find, we get a better error message
We could handle errors in the application_controller class

In show, put in a link that goes back to the list:


In the list:

Create a form so the user can enter something:
This would be the new action

In form_for call, you provide the name of a model

The data we receive will come through the params hash
Recipe: route, controller, action, view

For the form:

Put this one above the “stations/:id” route
In controller:

Create a file app/views/stations/new.html.erb

To handle the form, put in another route

Create in controller:

Here is the form:

Returning JSON data

Example: Twitter

(BTW Brian Hogan)

There’s a URL you can use to get a JSON representation of someone’s twitter feed for instance.

Represents Objects in Text:

Some Common JSON Notation:

[ ] – array
{ } – hash
: – in between a key-value pair

in the index method of controller, use the respond_to method to specify what we could respond to

To request json from the browser:

also works for XML

To request xml from the browser:

To delete a station:
in show:

So in routes:

So add a destroy method in controller

Code Academy Week 2 Notes Post 02

Methods always return something, even nil
Put an at sign in front of variable makes it an instance variable
Class names get upper case – but when you enter rails generate command you can make the model name lower case
model: class name is singular – this is a particular row in the database
The generators are pretty forgiving
But the pluralization is important – you need to get that right
Model names are singular, table name is plural
Model methods: new, save, all, first,
Landmark.all -> talks to the table
To populate database in the rails console:

Undocumented trick in rails console: type name of class and press enter. If there is a model class with that name, it will print info about class
Another way: pass a hash

Hash keys: Could be strings, people prefer symbols
symbol: like a lightweight string, faster to process, fewer methods you could run on it, like a number that’s easy to read
You still call with hash
He used “x” as variable name twice
The old value went away
Another way:

Parentheses are optional in Ruby
Using create will save it in one step
What if I have another landmark with the same name as an existing one?
Landmark.find(4) where the arg is the ID number
The IDs start at one
To list them:

To list one

How to delete?

But variable x still has data in it, even though that record is not in database
Or you could call Landmark.destory(id_name)
You could do Landmark.find_by_cost(15)
That would show anything with a cost of 15
The find_by methods will only give you the first that it finds
It dynamically makes methods via code generation = kind of metaprogramming

Some of the HTML is done by app/views/layouts/application.html.erb
The yield method puts our stuff in there
You can have different layouts for different controllers

How to select one and show just that one?
Go to controller file:

Make a new route:

That’s hard-coded

What about the controller? How to put that :id in call to Landmark.find?
Now, 5 is hard-coded in the controller. Here is the log:

The second time is better:

If you changed :id in the route to :jeff, you would get the same thing in the log except for timestamps, and

would be

So to get the id we send, put this in controller:


Model: singular, controller is plural
Model: name.rb, Controller: names_controller.rb

To catch a bad :id in controller show method:

That’s not the best way, but it works for now

Change routes.rb:


And for the other one:

This is only for Rails 3 and beyond
Put a link that takes us back to the home page:
IN the show template for show.html.erb
You could remove /public/index.html
and put this in routes.rb:

rake has a lot of good stuff

will print the routes

so if the route has a name, you can use it in a link_to method call

You need to run rake routes to see which ones have names
You could also do landmarks_path
This will just create a relative URL

You can give a route a name:

In the index when we iterate, we could:



Let’s add a form
What should the URL be?
So put it in the routes.rb

So put an action “new” in the landmarks controller
and create a file app/views/landmarks/new.html.erb

When to add a controller instead of a new method?
Is the activity still related to the same type? Or is it a new thing?
We do not need the “form” tag

Go to routes:

put a create method in the controller
The new method was just for the form
In log:

ActionView::MissingTemplate (Missing template landmarks/create, application/create with {:handlers=>[:erb, :builder, :coffee], :formats=>[:html], :locale=>[:en, :en]}. Searched in:
* “/home/ericm/ruby/codeAcademy/tth/second/app/views”
In parameters, there is

So our data is in the hash. The data is the value of a hash, which itself is another hash
Do this:

You could do:

At the end of the create method

the URL must be a named route

The tag is

How to get rid of a landmark:
Is the show.html.erb

In routes:

But there is a name conflict in the route – we will look at this next week

To update in console: could get it, change it, save
or: call method update_attribute

Code Academy Week 2 Notes Post 01

Here are my notes for the first day of week 2 at Code Academy.



Classes: Fundamental

Ruby On Rails:
Why use it?
Database-Backed Web Applications
Convention Over Configuration
Agile Development

Rails quickstart:

go to http://localhost:3000

Webbrick is great for development. There is Apache, nginx for production.

The index arg is a method that will be created in the controller
There is also an index file in app/views/landmarks
Use plural for controllers
So we could view this at http://localhost:3000/landmarks/index

For a request, the route config will pick a controller

Models: software objects that represent real-world objects. We use Ruby classes to define models.
They go in the $APP_NAME/app/models folder
In models folder, create a file landmakrk.rb
Controllers are plural, models are singular
Make a model class, then fire up the “rails console”
like “rails server” you should be at the top level of the app
In the html.erb files:

to print output of Ruby code:

This is like string interpolation, but it is called “embedding Ruby” when it is in an erb file
The variables are local to that view file. They die once the view is rendered
Controllers job is to decide what data to present, view decides how to present

Each method in controller corresponds to a view file – that is pairing
Instance variables in method are readable by the view
Now getting data from database

could run for help:

This creates a file in db/migrate/20120117171507_create_landmarks.rb
and app/models/landmark.rb
Here is the migration file:

How to run it? with rake (or ruby make)

Now go to rails console:

The object has fields, even though the model class is pretty empty

you get the attr_accessors automatically:

You can add stuff to database via the console

To list rake targets: rake –tasks

To delete database and recreate it with same structure:

Now, how do I make a page for each landmark?
How about a show page?

in config/routes.rb
So we need a file app/view/landmarks/show.html.erb and a show method in the Landmarks controller
Action: Is method in controller and corresponding view page

Code Academy HTML5 notes

Part of Code Academy is an HTML5 class that happens on Monday nights. The first class was on a Wednesday. I went to that one, and I plan on going to more in the future. The lecturer is Shay Howe, a designer at Groupon.