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
Off to a slow start. Checked SO and ran the below commands for a fix:
$ 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.
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:
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:
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.
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:
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.