Ruby On Rails for the MEAN stack developer
Ruby On Rails has been around since about 2006 and it is a tried and tested way to build web applications. In this tutorial we’re going to use the popular Bootstrap 3 UI library and Ruby On Rails 4 to create a server and database. The app will display a prepopulated list of tasks. In future lessons we will go through adding and modifying tasks.
tl;dr SOURCE CODE
Questions? Hit me up on twitter
First step, check that you have ROR and Postgres installed, create a new project with a postgres database:
That failed with a
$ bundle install
Off to a slow start. Checked SO and ran the below commands for a fix:
rvm get stable
$ bundle install is the rails version of npm install. Instead of npm modules you use ruby gems. They’re defined in the Gemfile.
Then set up the database with some more rails magic:
Whenever you change your schema (database) you have to run these commands so rails can write out SQL queries for us. (That’s right we’re in structured database land.)
If we open up http://localhost:3000 we will see the default ROR home page.
Now make a todo model, this will be a table in the database. The model fields will be some text and a boolean if the task is completed. After generating the database model run the migration command so ROR can update all our SQL.
$ rails generate model Task title:string completed:boolean
Okay cool now let’s display a list of tasks on the homepage. The ROR way to do this is make a Task controller. We’re going to add an ‘index’ method when we create the controller:
$ rails generate controller task index
This generated lots of crap and we’re using coffeescript like real Ruby people — ew.
So then even though the task controller looks like this:
class TaskController < ApplicationController
the page still renders:
Sexy.Okay so now edit app/views/task/index.html.erb like the Rails machine tells us.
The index file can look something like this.
It will be ugly cause we have no bootstrap yet.
The last line of your Gemfile:
In app/assets/stylesheets/application.css add:
All the instructions can be found in official bootstrap-sass repo. We also have to change the application file name to a SASS extension cause… well we’re using SASS.
$ mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss
Now the word “Taks” should be centered in the page.
We want to show some tasks initially. We can use
$ rails console to modify the database from the command line. Another way we can do it is with db/seeds.rb. In that file paste in our default Tasks:
tasks = Task.create([
Then populate the database with:
Update the index file to render our task titles:
Okay now we have a list of tasks. In upcoming lessons we will go through adding tasks and toggling their completion status.