Rails is an open source MVC framework built on the ruby programming language. It is used by as the framework of choice for many different organisations such as:
- Airbnb
- Hulu
- Airtasker
The reason for its popularity is because it allows developers to rapidly develop dynamic web applications and web sites. It does this by following two main principles of convention over configuration which we will talk a bit more about in a second and DRY.
What does DRY stand for?
Do Not Repeat Yourself
And what does that mean?
We abstract our code in such a way so that we avoid writing the same lines of code over and over.
Rails also has built in commands that can generate lots and lots of boilerplate for us so we don’t have to write it every time we need to create a new app or if we want to add features to an existing rails app.
What is boilerplate?
Boilerplate is a unit of code that can be included in many places with little to no alteration. Think about when we were creating our HTML websites. There was certain code we need to write for every page. Wouldn’t it be better if that code was auto generated for us so we didn’t have to write it?
Another great thing about Ruby on Rails is that there are many gems that extend the features of our application that doesn’t require much effort from the developer. We can add in to our app sending emails, logging in with facebook, taking payments and much more.
Rails is considered an opinionated framework and you will hear all the time in the rails community the phrase, “the rails way”. It makes the assumption that there is a "best" way to do things, and it's designed to encourage that way - and in some cases to discourage alternatives. To better understand lets talk about what convention over configuration is and why we would want this
Convention over configuration is a simple concept that is primarily used in programming. It means that the environment in which you work (systems, libraries, language…) assumes many logical situations by default, so if you adapt to them rather than creating your own rules each time, programming becomes an easier and more productive task.
The goal is to decrease the number of decisions the programmer has to make and eliminate the complexity of having to configure each of the areas of application development. The immediate result is that you can create many more things in less time.
It does require a greater learning curve at the beginning because you need to become familiar where everything located and the convention being used. In any case, to use a system in which most things are pre-configured is always more productive than to use a completely open system in which you have to set all the rules and take all decisions.
Creating A Rails App
Before we begin it is important to know where we can find all the documentation associated with Ruby on Rails. We can find the documentation here: https://guides.rubyonrails.org/.
A really important key thing to know is that we are using Rails V5.2. Remember the initial number in versioning is considered a major change and code written for this version may be incompatible for different major versions. This is especially true between Rails V4 and V5, so do not use V4 as your code probably won’t work in V5.
Another important resource of information for creating a new Rails app is actually within the help option of the rails command.
rails -h
The output shows you how to create a new Rails app along with some different options we could use during the creation process.
For the moment lets create a new Rails app using all of the default settings.
rails new first_app
Awesome! It’s all installed. Lets cd into the directory.
cd first_app
And then lets run the help option again.
rails -h
What black magic is this! We get a whole bunch of other options we didn’t have last time. That is because rails is smart enough to know if you are in a rails directory or not when you you are running the rails command.
Lets start up our Rails application.
rails server
This boots up puma which is the web server RoR comes pre-configured for.
What is a web server?
A web server allows a directory within our machine to be accessible by the network (internet in most cases). This is how we can host websites and web app that are accessible from anywhere in the world!
Within the output of the web server in the console you should see which address it is listening on. By default it is localhost:3000
.
What is the default IP address of localhost?
127.0.0.1
If we go to the address in our web browser we can see our Rails application is running!
Lets take a deep look into our Rails application and go through each file and understand exactly what it is used for.
Go through all of the files in the Rails application, below is a generic table of each section and what it is for. This has been pulled directly from the Rails documentation.
File/Folder | Purpose |
---|---|
app/ | Contains the controllers, models, views, helpers, mailers, channels, jobs and assets for your application. You'll focus on this folder for the remainder of this guide. |
bin/ | Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy or run your application. |
config/ | Configure your application's routes, database, and more. This is covered in more detail in Configuring Rails Applications. |
config.ru | Rack configuration for Rack based servers used to start the application. For more information about Rack, see the Rack website. |
db/ | Contains your current database schema, as well as the database migrations. |
Gemfile, Gemfile.lock | These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the Bundler website. |
lib/ | Extended modules for your application. |
log/ | Application log files. |
package.json | This file allows you to specify what npm dependencies are needed for your Rails application. This file is used by Yarn. For more information about Yarn, see the Yarn website. |
public/ | The only folder seen by the world as-is. Contains static files and compiled assets. |
Rakefile | This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application. |
README.md | This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on. |
test/ | Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications. |
tmp/ | Temporary files (like cache and pid files). |
vendor/ | A place for all third-party code. In a typical Rails application this includes vendored gems. |
.gitignore | This file tells git which files (or patterns) it should ignore. See GitHub - Ignoring files for more info about ignoring files. |
.ruby-version | This file contains the default Ruby version. |
Gems Revision
Remember gems are just packages of code pre build for us by other developers that we can download and include in our applications. In Ruby there are generic gems that can work in any Ruby application and then there are gems that are specifically for Ruby on Rails. Both of these gems are downloaded the same way though.
In Ruby on rails we use the bundler package management gem to install and keep track of the gems we are using within our application. These gems are added to our Gemfile.
Lets add another gem to our application through bundler. Remember we need to be in the same directory and our Ruby on Rails application before we run the below command.
bundle add faker
Today we will create the app with books. Today's app will display books. Additional features will be added as more Rails features are covered.
Create new repo in github
- choose a naming convention that will help you find and recognise the project
- optional private
- don't add a gitignore or readme. Rails will =create these for us
At the command line move to the area where you will keep your rails projects
/Users/leahgarrett/Documents/ca/rails
Clone the repo
git clone git@github.com:leahgarrett/rails-01-books.git
Make the rails app
rails new rails-01-books --database=postgresql
Move into the directory of the new app
cd rails-01-books
Check status to see what new file were added
git status
Open Visual Studio Code and explore the files created
code .
At the command line run the server
rails server
Open the app in a browser 'http://localhost:3000/'
The following error is displayed
FATAL: database "rails-01-books" does not exist
Create the database
rake db:create
Now run the server
rails server
Working!
Lets save this:
git add .
git commit -m 'initial commit - app running'
git push
Note: If you have an error accessing origin when when you push .
git remote add origin git@github.com:leahgarrett/rails-books.git
.
git push -u origin master
.
Creating the controller
rails generate controller books
Update the file books_controller.rb
to add the index method for the landing page
class BooksController < ApplicationController
def index
end
end
To make the landing page the defaul page for the app update the config file routes.rb
to now look like
Rails.application.routes.draw do
root to: 'books#index'
end
In the Views folder in the books
sub-folder create a new file
index.html.erb
Open the file and add a heading
<h1>My Books</h1>
Run the app.
Use Visual Studio Code to view the new files created and changed.
Lets save this:
git add .
git commit -m 'first view and controller added'
git push
Generate the model
rails generate model Book title:string author:string publisher:string genre:string description:string
Run the created migration
rake db:migrate
Add faker to the app
bundle add faker
Add seed data to seeds.rb
puts "Start of Seeding..."
Book.destroy_all
50.times do
params = {
title: Faker::Book.unique.title,
author: Faker::Book.unique.author,
publisher: Faker::Book.publisher,
genre: Faker::Book.genre,
description: Faker::Lorem.paragraph
}
puts "Creating Book: #{params}"
book = Book.new(params)
book.save
end
puts "Seeding Over"
To run the seed data
rake db:seed
Update the default view
<h1>My Books</h1>
<div class="book-list">
<% @books.each do |book| %>
<div>
<h2><%= book.title %></h2>
<h3><%= book.author %></h3>
<a href="/books/<%= book.id %>">
Details >
</a>
</div>
<% end %>
</div>
Verify it runs
Lets save this:
git add .
git commit -m 'book model setup'
git push
Update the controller
class BooksController < ApplicationController
def index
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
end
Add a view in the books folder show.html.erb
Edit the new file adding the following
<div class="book-detail">
<h2><%= @book.title %></h2>
<h3><%= @book.author %></h3>
<h3><%= @book.publisher %></h3>
<h4><%= @book.genre %></h4>
<p><%= @book.description %></p>
<a href="/">
< Back
</a>
</div>
Update routes.rb
Rails.application.routes.draw do
root to: 'books#index'
get '/books/:id', to: 'books#show'
end
Confirm it works
Lets save this:
git add .
git commit -m 'list and detail view wired up'
git push
We will add forms tomorrow as part of the challenges tomorrow
Add styling for the Book List and Book Details classes.
Build a blog folllowing the rails guides getting started tutorial: https://guides.rubyonrails.org/getting_started.html