Rails

1. Hello-world app

Start a new project

gem install rails
# or gem install rails -v 6.0.0

# confirm rails version
rails -v
Rails 6.0.2.2

# also need to install yarn

rails new my_app

cd my_app
bundle install
rails s

# go to http://localhost:3000
default Rails directory structure

Gemfile

Hello-World app

2. Toy App

models

  • users: id (int), name (string), email (string)

  • microposts: id (int), content (text), user_id (int)

page URLs for the Users resource
RESTful routes provided by Users resource

More models

MVC in Rails

3. Sample App

User Model

Why we need to enforce database level uniqueness in addition to ActiveRecord uniqueness validation?

  1. Alice signs up for the sample app, with address [email protected].

  2. Alice accidentally clicks on “Submit” twice, sending two requests in quick succession.

  3. The following sequence occurs: request 1 creates a user in memory that passes validation, request 2 does the same, request 1’s user gets saved, request 2’s user gets saved.

  4. Result: two user records with the exact same email address, despite the uniqueness validation

Solution: enforce uniqueness on db level by creating index on the email column, then require that index to be unique.

(If the migration fails, make sure to exit any running sandbox console sessions, which can lock the database and prevent migrations.)

Password

Sign up

Production-Grad deployment

Force browser to use SSL

Log in (sessions)

Advanced login - remember me

Plan for creating persistent sessions appears as follows:

  1. Create a random string of digits for use as a remember token.

  2. Place the token in the browser cookies with an expiration date far in the future.

  3. Save the hash digest of the token to the database.

  4. Place an encrypted version of the user’s id in the browser cookies.

  5. When presented with a cookie containing a persistent user id, find the user in the database using the given id, and verify that the remember token cookie matches the associated hash digest from the database.

Update, show, and delete users

Microposts

Once we have user/micropost association (a user has many microposts), we have the following methods

Active Storage

User following users

4. Rails-flavored Ruby

Strings

Methods

Other data structures

Arrays and Ranges

Blocks

Hashes and symbols

helper function revisit

Ruby Classes

Other cool stuff Rails offer

Last updated

Was this helpful?