August 29, 2016 |
  • Technical

Tech Talk - An Introduction to Rails

Let me start by saying I love Rails. It’s flexible, powerful and has a wonderful attribute known as “Rails magic”. It’s flexible for people first learning the framework and yet highly customizable for advanced users building powerful applications. To give you an example of what can be built with Rails maybe you’ve heard of a few of these: Twitter, AirBnB, Kickstarter, Digital Ocean, Shopify and Hulu? They’re all built with Rails 1. A classic Rails app follows the MVC pattern which you may have heard of before. The M stands for Model, this defines a thing in your application. I like to think of proper nouns when deciding what my models should be. The V stands for View, this sounds pretty self-explanatory but it’s where the data gets displayed to a user. Lastly the C stands for Controller, think of this as the intermediary between the data of an application and the view. It tells the application what information to send and where to send it depending on what a user does. That’s probably enough of my blabbering. Let’s get started building a basic application that highlights some of what I love the most about Rails. I’m going to skip the Ruby installation steps as I’d be repeating what is already written well other places on the internet. Here are a few good tutorials to follow along with for the installation of Ruby and the dependencies required. Linux: gorails.com/linux Mac: gorails.com/mac Now that Ruby is installed, it’s time to install Rails. Open your terminal and enter this command: `gem install rails -v 4.2.6` Once successful, rails will be installed on your computer! Unfortunately the powerful “rails” command won’t be available yet. We need to tell your newly created ruby environment to use it. Simply run this command: `rbenv rehash` The last step of the Rails Instillation is to check that everything worked as expected. Run this command: `rails -v` You should see **Rails 4.2.6** returned in your terminal. Do you? Yes? Great! We now have version 4.2.6 of Rails installed. We’re ready to start building. ### The Application ### Let’s build a simple task-list application. We’ll use the “rails” terminal command to scaffold a new application for us. To start, navigate to the folder on your computer you want the application to live (it is entirely your preference). Once there, run this command: `rails new task-list` Rails will create all of the directories and files of a basic Rails installation. You will see a `bundle install` line appear, this is rails installing the dependencies required for the rails application to work. `cd` into the new folder created for the application and open the files in your favorite text editor. Let’s start by making sure the task-list scaffolded correctly. Spin up a rails server by running the command: `bin/rails s` this is the same as running`bin/rails server` WEBrick will boot-up the server and the standard rails welcome will be available at http://localhost:3000 in your browser. (image here) Woah, we’ve got a working rails application. This is one of the things I love about Rails, things just work. We wrote two commands and had a working application right out of the box. ### Now let’s make it do stuff ### First, we need to shut down the rails sever running. To do this open the terminal window running the server and press `Ctrl + c` on a linux machine or `control + c` on a Mac. You will see a shutdown message and your terminal should return to normal. Great, now let’s think about what we want this task list to be able to do. For the purposes of this demo a user will be able to: * Create a new task * View the already created tasks * Delete a task Simple? Yes, but feel free to add extra functionality once you feel comfortable with these basics. Get ready for some more rails awesomeness. Let’s create the model for our task list. The list of tasks would be made up of many individual Task items. So let’s make Task our model. To create a model rails has a wonderful command, simply type: `rails g model Task` or `rails generate model Task` A few things will be created once this command is run but for this demo the important ones are: * db/migrate/20160603174434_create_tasks.rb * app/models/task.rb This first file created is where we tell our database (don’t worry, one was already created for you during the rails new step earlier!) what fields we want a task to have. Let’s open that file in our text editor it should be the only file in the `db -> migrate` folder. You’ll see rails has already generated some code for us, Awesome! We want our task to have a title and a description. So let’s add those to the file in the create_table block. Let's make the title a `string` and the description a `text` (the text is comparable to a text area).

class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :title
t.text :description
t.timestamps null: false

view raw 20160603174434_create_tasks.rb hosted with ? by GitHub

Now we need to tell our database to create this database table called Tasks. Save the file and open up the terminal again. Run: `rake db:migrate` Did it work? Yuussss! Now we have a tasks table in our database! Lets open the model file for our task that was generated with the migration file. `App -> models -> task.rb` Wait, there’s no real code here, Just defining a class? I thought models were for defining objects? You are absolutely correct they are but this is another part of the “Rails magic” I spoke to earlier. Rails utilizes a fantastic piece of software called ActiveRecord. ActiveRecord is a layer of software that does all the heavy lifting when it comes to defining specific attributes a model has. I think of it as the link between the database and the application. Lets think about a Task for a second. We want to make sure a task at least has a title. We ensure this through something called validations. The validation in our case will be the 'validates presence of' method. I'm sure you've probably already guessed validates to a truthy value if the field has a value. Lets add this validation to our Task model we have open and add a brief error message.

class Task < ActiveRecord::Base
validates_presence_of :title, :message => "A title must be entered"

view raw task.rb hosted with ? by GitHub

Now every new task created will have this validation check run and if it passes the task will be added to our database, if not that error message will be displayed instead. Okay, We’ve got our model and database set up for Tasks. Now we should set up our view and controller to show the tasks. But before we do, we need to define our routes for our view’s to live on. To do this open our applications routes file `config -> routes.rb`. Simply add `resources :tasks` to the routes.rb file and rails will automatically generate the RESTful routes associated with our Task model. Awesome.

Rails.application.routes.draw do
resources :tasks

view raw routes.rb hosted with ? by GitHub

Lets test to make sure the routes were set up how we expected. Run the command: `rake routes` from your command line. You should see something similar to this appear in your terminal. ``` prefix Verb URI Pattern Controller#action tasks GET /tasks tasks#index POST /tasks tasks#create new_task GET /tasks/new tasks#new edit_task GET /tasks/:id/edit tasks#edit task GET /tasks/:id tasks#show PATCH /tasks/:id tasks#update PUT /tasks/:id tasks#update DELETE /tasks/:id tasks#destroy ``` Before we continue let me explain what is going on here. The prefix column are the rails helper methods that allow you to dynamically link to that specific page anywhere in your app. Simply append `_path` to the end of one of those prefix items and you are off to the races. `tasks_path` is the same as visiting `http://localhost:3000/tasks` . Awesome. Now we need to set up our controller and views to match those routes we created. To do this we’ll use another rails command: `rails g controller Tasks` or `rails generate controller Tasks` Our controller has been created for us. Let’s open it up and see what’s there. `app -> controllers -> tasks_controller.rb` Not much has been created for us but that’s okay, we’ll build it. As you can see on the routes we created earlier there were controller actions matched up to the different HTTP requests and to the different routes. Let’s start with the index action. The general rule is an Index action should return a group of or all of a certain resource. In our case our resource is a task. ActiveRecord has an awesome method `.all` which returns all items in a database of a certain resource. To call this we create an index method in the controller. We assign the instance variable tasks to the result of Task.all or in regular English, all the tasks are now called tasks. Let’s fill in the rest of the controller for the new, create and destroy methods.

class TasksController < ApplicationController
#GET /tasks or using tasks_path
def index
@tasks = Task.all
#GET /tasks/new or using new_tasks_path
#this is where our new task form will live
def new
@task = Task.new
#POST /tasks or using tasks_path
#once the new task has been submitted using POST, the create action takes over.
def create
#we create a new Task object and pass it paramaters defined at the bottom of the page (see below for description)
@task = Task.new(task_params)
if @task.save
#if newly created task is saved successfuly redirect back to the tasks list page and notify the user.
redirect_to tasks_path, notice "#{@task.title} was created!"
#if the newly created task doesn't save render the new task form again.
render :new
#DELETE /tasks/:id or using task_path(task-to-delete)
def destroy
#find the task that has the ID
@task = Task.find(params[:id])
#after the task is destroyed return back to the tasks list page.
redirect_to tasks_path
# This protected code block is called strong params. Essentially it limits what parameters can be passed to the database. Double check your spelling!
def task_params
params.require(:task).permit(:title, :description)

view raw tasks_controller.rb hosted with ? by GitHub

Now that we have our routes set up that agree to the routes we created earlier, lets create our views. In Rails the controller GET actions line up with the view names. If we have an index action we should have an index view. Clear as mud? Great, let’s build these views starting with our index view. Rails utilizes a file extension called ERB which is what allows us to use ruby variables in our html. For our purposes all our view files will end with .html.erb for example. Our index view will be called `index.html.erb`. We’ll create a very basic page that has a link to create a new task and list all the tasks already created. Create this index.html.erb file in the `app -> views -> tasks` folder

<!--creates an <a> tag around the text "new task" and points it to eh new_task_path defined in our routes -->
<%= link_to "new task", new_task_path %>
<!--loops through each of the tasks returned from the database and passed to the view from the tasks_controller index action -->
<% @tasks.each do |task| %>
<!-- for each task put the title in an h3 tag -->
<h3><%= task.title %></h3>
<!-- for each task put the description in a p tag -->
<p><%= task.description %></p>
<!-- for each task add a delete button that uses the DELETE Http method (GET is default for link_to helper methods) -->
<%= link_to "delete", task_path(task), method: :delete, data: {confirm: "Are you sure?"} %>
<% end %>

view raw index.html.erb hosted with ? by GitHub

Hopefully the comments on this GIST help with explaining what is going on here. You’ll see these funny combination of characters on the page `<% %>` and `<%= %>` this is Rails’ way of telling ERB there is ruby code between these markers that needs to be run as ruby code and not as HTML. The `<%= ruby code %>` will display what is between on the page where `<% ruby code here %>` will not be displayed on the page. This seems like a good time to spin up the rails server again and test that our pages are working. `bin/rails s` Visit `http://localhost:3000` wait… why are we still seeing the default rails home page? Well that’s because we don’t have a root path defined, rails renders its default page here by default. Lets visit http://localhost:3000/tasks to see if we get any errors. Did you see a blank page? GREAT! Let’s fill in our new task form and add some tasks. `app -> views -> tasks -> new.html.erb`

<%= form_for @task do |f| %>
<%= f.label "title *" %>
<%= f.text_field "title" %>
<%= f.label "description" %>
<%= f.text_area "description" %>
<%= f.submit "Create" %>
<% end %>

view raw new.html.erb hosted with ? by GitHub

Refresh your browser and click the new task button. Do you see the form? Yusss! Look at that, we have created a working rails application that interacts with a database in about 30 minutes. Pretty neat hey? Go ahead and play around with adding tasks and deleting tasks. I pushed the application to a github repo [here](https://github.com/JoeyBy/task-list-demo) if you would like to see. There are many, many amazing things about Rails I simply was not able to touch on in this article. The `rails scaffold ... ` command, ActiveRecord associations, the list is endless in my eyes. Check back soon for more examples. *1http://stackshare.io/rails*

IIUp next

Keep Reading

Prev Post   
Get Creative wi.....
  Next Post
Talking Millenn.....
facebook-app-symbol twitter up-arrow phone-call