Rails Review

This is a reference guide for everything you've learned so far in Rails.

Rails Commands

new command

This will create a new Rails project in the project_name folder.

rails new project_name

generate command

Rails generators will automatically create files for you in the correct places.

We most often use the model and migration generator. The controller generator is less useful, as it adds many files you don't need, and it doesn't properly set up routes.

Model generator

The model generator will automatically create model class files, and their create_table migration. This is really helpful!

rails generate model ModelName name:string count:integer description:text

Migration generator

Migrations are used for modifying the structure of your database. Since the model generator generates a create_table migration, the migration generator is most commonly used for modifying existing tables, such as adding new columns.

$ rails generate migration MigrationName

Just like ModelName, MigrationName must be TitleCase or snake_case.

Special Names for Migrations

The migration generator offers several helpful shortcut names, such as AddAuthorToArticles, which will automatically create a migration for you based on the name. This can be a bit confusing until you get the hang of it, but just remember convention over configuration. Here's an example:

$ rails generate migration AddAuthorToArticles author:string

This will automatically create a migration that adds the author:string attribute to the articles table.

Other Options

The migrations generator has many different options. See the Migration section of the Rails Guides for very helpful documentation.

server command

To start a Rails server:

$ rails server

You can also use a shorthand command for most Rails commands. This will also start a server:

$ rails s

console command

The Rails Console is an incredibly valuable and versatile tool for exploring your Rails app and developing new code.

$ rails console
# OR
$ rails c

Using Pry with the Rails Console

Pry makes the Rails console about fifty times better . To use Pry with the Rails Console, make sure you add it to your Gemfile here:

# Gemfile
group :development, :test do
  gem 'pry-rails'

  # ... your other gems
end

Be sure to run bundle every time you change your Gemfile!

Some useful pry-rails commands:

Routes

Routes are used by Rails to define the URLs of your web site, which are like the endpoints of your application's API. When a browser visits an URL that matches one of your routes, Rails will instantiate the matching controller, and invoke the action method specified by the route.

Routes can be specified manually like this:

get 'welcome/index'
get 'welcome/about'

In this case, the WelcomeController will be instantiated, and the index or about method will be invoked.

RESTful Routes

Generally though, we want to use a RESTful resource.

resources :articles

This means Rails will automatically generate routes for the seven restful routes (not to be confused with the seven deadly sins):

HTTP Verb Path Controller#Action Used for
GET /articles articles#index display a list of all articles
GET /articles/new articles#new return an HTML form for creating a new article
POST /articles articles#create create a new article
GET /articles/:id articles#show display a specific article
GET /articles/:id/edit articles#edit return an HTML form for editing a article
PATCH/PUT /articles/:id articles#update update a specific article
DELETE /articles/:id articles#destroy delete a specific article

CRUD/RESTful Routes

Each of the Seven Restful Routes corresponds to one of the data actions in CRUD. Here's a list of how they relate!

Further Reading

As always, Rails Guide's has an excellent page about routes, called Routing from the Outside In.

Controllers

Controllers are the "dispatchers" of the application.

  1. Prepare all your data by using models to read the database
  2. Passes your data on to your view templates to be parsed by ERB.
  3. Renders the view templates
  4. Sends the resulting HTML back to the server

We call the methods in a controller an action method. However, an action method is not a special kind of method, it simply means that there is a route that corresponds to that method. So index is an action method if there is an index route.

Instance Variables

Like any object instances, you must use @instance_variables for your variables to be available outside of the method. If you want a view template to be able to access a variable, it must be an instance variable!

Params hash

The server passes in a list of parameters to your Rails app. Rails allows you to access these params with the params attribute available to any of your controller methods.

params contains information about the HTTP request, but it is most often used for forms.

Strong Parameters

Strong parameters prevent hackers from hacking your web site. This is such a big problem that Rails will prevent you from passing the params hash directly to model methods!

To use strong parameters, you use the require and permit methods on the params hash.

def article_params
  params.require(:article).permit(:title, :text)
end

See the Rails Guide's section on Strong Parameters for more information.

Views

Views are simply HTML templates that also allow you to embed Ruby using ERB.

Naming View Templates

Because of convention over configuration, you should name your view templates based on the action methods of your controllers. As long as your view template names match the action methods of your controller, Rails will automatically know when to render them.

This means that you usually have at least these four view templates in each controller's views folder.

Why only those four? The other RESTful Routes are redirects. create and update both redirect to show after the method runs. The destroy method redirects to the index page after the method runs.

Using Ruby in a View

To use Ruby in a view template, you have two tags available to you.

The most common use of ERB in Rails is to output data from models. Here's an example:

<div id="content">
  <% @articles.each do |article| %>
    <article>
      <h1><%= article.title %></h1>
      <p><%= article.text %></p>
    </article>
  <% end %>
</div>

While you are encouraged to put Ruby code in your views, you should do the barest minimum amount of Ruby coding possible to get your desired results. More complex Ruby code should either go in the controller, or in a custom helper method.

Things that are ok to do in a view template

Example things you should do in the Controller instead of the View

Models

Models are how you interact with your database programmatically. Instead of having to manually write SQL statements for all of your database CRUD, you can instead use basic Ruby objects that Rails uses to represent your database CRUD!

Attributes

All attributes of your models are read from the database! You do not manually assign attributes to a model through Ruby code. Convention over configuration!

See below about Migrations for more.

CRUD methods

All Rails models have a large set of CRUD methods available to you. Here's an example:

# Create
Animal.create name: "Giraffe", description: "Has a realllly long neck."

# Read
giraffe = Animal.find_by name: "Giraffe"

# Update
giraffe.update name: "Baby Giraffe"

# Destroy
giraffe.destroy

Common class methods

Instantiating

Querying

Common instance methods

Further Reading

All of these methods and many more can be found in the Rails Guides for the Active Record Query Interface.

Migrations

Migrations are crucial to understanding how to use databases with Rails, but can also be pretty confusing without experience using databases. It's a Catch-22!

Migrations are used primarily for modifying the structure of your database. Remember that we don't explicitly create attributes for our models, and that the database is the authoritative source of information for our models.

In order to modify the database, we have to create a migration. Migrations are most often used for:

Migrations are a complex subject, and they have their own dedicated Rails Guide. See the Active Record Migrations guide for much more information about how to use them.

Activating Migrations

Once you have created migrations, you must activate them. You do that with this command:

$ rake db:migrate

Modifying existing migrations - DONT!

You should never ever change an existing migration after you've commited it to git!!

Why?

Migrations are the authoritative source of structural changes in your database. Once you've saved it into history, you've also commited that structure of your database into history forever.

Here's a simple example of what can go wrong:

  1. Developer (A)lbert creates a migration that changes a table column, and commits the migration to git.
  2. Developer (B)etty pulls in Albert's changes, runs her migrations, and begins writing code.
  3. Albert then goes back and changes his migration that he already commmited, and then commits that change.
  4. Betty downloads Albert's changes, and realizes that Albert changed the past. Betty would have to undo her migrations, and run them again, which will likely mean her database is in an incorrect, and potentially unfixable state.

Betty has trusted Albert not to change the past, but he created a paradox.

Remember,

You should never ever change an existing migration after you've commited it to git!!

If you need to modify the structure of the database again, make another migration!

Seeds

Seeds are a simple way of adding default data to your database. During development you will throw away your database over and over again as you modify the structure, or have old data that you were playing around with in the Rails Console, or many other scenarios.

Seeds allow you to create a simple set of default test data.

# seeds.rb

# You usually want to delete all of the data before you seed,
# otherwise you'll end up with duplicate records!
Article.delete_all

# We use create! so an error is raised if the save fails.
# create - returns false if the save fails
# create! - raises an error if the save fails

Article.create! title: "Bruskis Climb Lion's Head", text: "They got to the top!"
Article.create! title: "Delicious Breakfast", text: "Students love Knead"

Activating Seeds

To activate your seeds, you must run the appropriate rake command.

$ rake db:seed

That's it!