How To Make Web App Ruby Rails

Ruby on Rails Tutorial: Make a Ruby on Rails Web App

Ruby on rails has been a popular way to develop web apps for a long time. It has garnered even more popularity in recent years as the base for many well-known applications and websites like Redmine Project Management and Twitter. A lot of developers now use it to make unique and powerful Ruby on Rails web apps. In this Ruby on Rails tutorial we will be taking a deeper look into “What is Ruby on Rails?” along with how to develop your own basic Ruby on Rails web app. First thing’s first, however… What is a web app?

What is a Web App

A web app (short for web-application) is a computer program a user runs in a web browser. Popular web apps include email, online sales or eCommerce websites, online auctions such as eBay, wikis, instant messaging services, and much more. Web apps can be programmed in a wide variety of languages such as PHP, Java, JavaScript, and Ruby, among others. However, for the purposes of this Ruby on Rails tutorial, we are going to look at Ruby on Rails… (duh). So what exactly is the difference between Ruby and Ruby on Rails?

What is Ruby on Rails

Ruby on Rails is an open source framework for the programing language Ruby. It provides a large, flexible library of functions and features that have already been developed, which can easily and quickly be implemented into almost any application. It basically does for Ruby what CakePHP does for PHP or JQuery does for JavaScript.

Advantages of a Ruby on Rails Web App

Why should you choose to make a Ruby on Rails web app? What makes it better or cleaner than using PHP, Python, or just plain Ruby? Well, when compared to PHP, Ruby is fast… like, really fast! Where a PHP app may require up to 4000 requests per second, a similar Ruby app can run at around 200. That means Ruby can do the work of a similar PHP web app almost 20 times faster! Using Ruby on Rails over Python is often also a popular choice because Python tends to get a bit cumbersome and become somewhat inelegant to read. Ruby also tends to be more on the cutting edge and willing to embrace new trends. Also, if you are going to use Ruby, you are better off going all in on Rails too, because then you can develop your Ruby on Rails web app faster with less hassle and need for debugging. With Ruby on Rails, much of the rough legwork has already been done for you!

Ruby on Rails Tutorial: Building a Basic Ruby on Rails Web App

Ruby on Rails is a full stack MVC web application framework. Full stack means you get everything: a simple web server you can use to test your apps, a database layer, testing framework, and an MVC based design. MVC stands for Model-View-Controller.

A model stores information. Models are stored in the database. Rails supports MySQL, PostgreSQL, or SQLite. Each model has its own class and table. Say we want to model a “game.” A game has things like a number of players, a start time, end time, teams playing, and a winner. These attributes become columns in the “games” table.

A view is the easiest part to understand. It’s what you see. It’s the HTML you generate to show the user what they need. It is also the only means the user has to interact with your Ruby on Rails web app!

A controller is the manager. It takes information and does some logic like CRUD, or maybe import some stuff from a file, add/remove permissions–you name it a controller can do it. Controllers are the part of your Ruby on Rails web app that does.

Ruby on Rails Tutorial – Step 1: Installing Ruby on Rails to a Linux Server

Now that we have covered the background of what Ruby on Rails is and why one might be best off making a Ruby on Rails web app, let’s start our Ruby on Rails Tutorial. First, before we do anything, we need to install Ruby on Rails somewhere. This is normally a somewhat complicated and in-depth process… but luckily, that is taken care of via a one-click SkySilk Ruby on Rails VPS.

First login to your SkySilk dashboard and select “Create Container” then just select a plan.

CLICK TO DEPLOY A RUBY ON RAILS VPS

When your plan is selected, choose a hardware configuration, or configure your own custom hardware.

Once you’ve got your hardware configured, select “Apps and Tools” then find “Ruby on Rails” and select it.

Now just enter the required info and hit “Go!”

That’s it, the first step is done.

Ruby on Rails Tutorial – Step 2: Creating a New Directory

So you’re going to want to SSH into your new container and finish setting up your Ruby on Rails instance. If you are having a bit of trouble doing this, check out this helpful support article on how to SSH.

READ: How to Access Linux VPS with SSH on Windows, Mac OS, and Linux

Once you gain access to your container through your SSH shell, it is time to install database support. Rails has support for all the popular DB’s, but for this example, we will use SQLite because it is lightweight.

sudo apt-get install sqlite3 sqlite3-devel

Ruby on Rails Tutorial – Step 3: Generating a Ruby on Rails Web App

Time to generate our app. The rails command creates a base application structure. All we need to do is be in a directory and run it like so:

$ cd ~/projects

$ Rails bookshelf #this will create a new directory named bookshelf that holds our app

$ cd bookshelf

It is important to note that the Rails default is an SQLite based app. You may be thinking, what if I don’t want that? The rails command is a generator. All it does is copy stored files into a new directory. By default, it will create sqlite3 databases in /bookshelf/db/development.sqlite3, /bookshelf/db/production.sqlite3, and /bookshelf/db/testing.sqlite3. Database connection information is stored in /bookshelf/config/database.yml. You don’t need to edit this file since it contains default information for an SQLite setup. It should look like this:

# SQLite version 3.x

# gem install sqlite3-ruby (not necessary on OS X Leopard)

development:

adapter: sqlite3

database: db/development.sqlite3

pool: 5

timeout: 5000

# Warning: The database defined as "test" will be erased and

# re-generated from your development database when you run "rake".

# Do not set this db to the same as development or production.

test:

adapter: sqlite3

database: db/test.sqlite3

pool: 5

timeout: 5000

production:

adapter: sqlite3

database: db/production.sqlite3

pool: 5

timeout: 5000

Notice there are different environments assigned. Rails has three modes: Development, Testing, and Production. Each has different settings and databases. Development is the default environment.

Now we will use the /script/server command to start a simple server for our application.

bookshelf $ ./script/server

# then you should see something like this. Rails will start a different server depending on your platform, but it should look something like this:

> Booting Mongrel

> Rails 2.3.5 application starting on http://xxx.xx.xx.xxx

> Call with -d to detach

> Ctrl-C to shutdown server

Time to visit the application. Point your browser to the IP address of your container to see the splash page. Now that the code is working on a basic level, it is time to delete the splash page and get started with some code.

bookshelf $ rm /public/index.html

Ruby on Rails Tutorial – Step 4: Models, Controllers, and the View

Our application needs data. This, of course, means models. Great, but how do we generate a model? Rails comes with some generators to common tasks. The generator is the file /script/generate. The generator will create our model.rb file along with a migration to add the table to the database.

A migration file contains code to add/drop tables, or alter/add/remove columns from tables. Migrations are executed in sequence to create the tables. Run migrations (and various other commands) with “rake”. Rake is a ruby code runner. Before we get any further, let’s start by defining some basic information for the books. A book has these attributes:

  • Title : String
  • Thoughts : Text

That is enough to start the application. Start by generating a model with these fields using the model generator:

bookshelf $ ./script/generate model Book title:string thoughts:text

# notice how the attributes/types are passed to the generator. This will automatically create a migration for these attributes

# These are optional. If you leave them out, the generator will create an empty migration.

exists app/models/

exists test/unit/

exists test/fixtures/

create app/models/book.rb

create test/unit/book_test.rb

create test/fixtures/books.yml

create db/migrate

create db/migrate/20091202052507_create_books.rb

# The generator created all the files we need to get our model up and running. We need to pay the most attention to these files:

# app/models/book.rb # where our code resides

# db/migrate/20091202052507_create_books.rb # code to create our books table.

Open up the migration file:

class CreateBooks < ActiveRecord::Migration def self.up create_table :books do |t| t.string :title t.text :thoughts t.timestamps end end def self.down drop_table :books end end

Notice the create_table :books block. This is where columns are created. An id primary key is created automatically. t.timestamps adds columns for created_at and updated_at. Now, run the migration using the rake task db:migrate. db:migrate applies pending migrations:

bookshelf $ rake db:migrate == CreateBooks: migrating ==================================================== -- create_table(:books) > 0.0037s

== CreateBooks: migrated (0.0038s) ===========================================

Cool, now that we have a table, let’s create a dummy book just for kicks in the console. The Rails console uses IRB (interactive ruby) and loads all classes for your project. IE you can access to all your models. Open the console like this:

bookshelf $ ./script/console

>> # let's create a new model. You can specify a hash of assignments in the constructor to assign values like this:

>> book = Book.new :title > 'Rails is awesome!' , :thoughts > 'Some sentence from a super long paragraph'

> # # and ruby will display it back

>> book.save

> true # now are book is saved in the database. We can query it like this:

>> Book.all # find all books and return them in an array

> [#]

>> exit # now that our model is saved, let's exit the console.

Now that we can create books, we need some way to show them to the user. We need a controller to display all the books in the system. This scenario corresponds to the index action in our BooksController (books_controller.rb) which we don’t have yet. Just like generating models, use a generator to create the controller:

bookshelf $ ./script/generate controller Books

exists app/controllers/

exists app/helpers/

create app/views/books

exists test/functional/

create test/unit/helpers/

create app/controllers/books_controller.rb

create test/functional/books_controller_test.rb

create app/helpers/books_helper.rb

create test/unit/helpers/books_helper_test.rb

# notice Rails created the file app/controllers/books_controller.rb? This is where we are going to define our actions or methods for the BooksController class

We need to define an action that finds and displays all books. How did we find all the books? Earlier we used Book.all. Our strategy is use Book.all and assign it to an instance variable. Why an instance variable? We assign instance variables because views are rendered with the controllers binding. You’re probably thinking bindings and instance variables…what’s going on? Views have access to variables defined in actions but only instance variables. Why, because instance variables are scoped to the object and not the action. Let’s see some code:

class BooksController < ApplicationController # notice we've defined a method called index for a BooksController instance. We tie this together with routes def index @books = Book.all # instance variables are prefixed with an @. If we said books = Book.all, we wouldn't be able to access books in the template end end

Now the controller can find all the books. But how do we tie this to a url? We have to create some routes. Rails comes with some handy functions for generating RESTful routes (another Rails design principle). This will generate urls like /makes and /makes/1 combined with HTTP verbs to determine what method to call in our controller. Use map.resources to create RESTful routes. Open up /config/routes.rb and change it to this:

ActionController::Routing::Routes.draw do |map| map.resources :books end

Routes.rb can look arcane to new users. Luckily there is a way to decipher this mess. There is routes rake task to display all your routing information. Run that now and take a peek inside:

bookshelf $ rake routes books GET /books(.:format) {:controller>"books", :action>"index"}

POST /books(.:format) {:controller>"books", :action>"create"}

new_book GET /books/new(.:format) {:controller>"books", :action>"new"}

edit_book GET /books/:id/edit(.:format) {:controller>"books", :action>"edit"}

book GET /books/:id(.:format) {:controller>"books", :action>"show"}

PUT /books/:id(.:format) {:controller>"books", :action>"update"}

DELETE /books/:id(.:format) {:controller>"books", :action>"destroy"}

# as you can see this command can display a lot of information. On the left column we have a helper to generate a url, then the HTTP verb associated with the url, then the url, and finally the controller and action to call.

# for example GET /books will call BooksController#index or

# GET /books/1 will call BooksController#show

# the url helpers are very important but we'll get to them later. For now know that we are going to create a /books page to list all books

Now we need to create a template to display all our books. Create a new file called /app/views/books/index.html.erb and paste this:

< for book in @books do >;

<%=h book.title %>

<%= book.thoughts %>

<% end %>

This simple view loops over all @books and displays some HTML for each book. Notice a subtle difference. <= is used when we need to output some text. <% is used when we aren’t. If you don’t follow this rule, you’ll get an exception. Also notice the h before book.title. h is a method that escapes HTML entities. If you’re not familiar with ruby, you can leave off ()’s on method calls if they’re not needed. h text translates to: h(text).

Time to run the server and see what we’ve got. Start the server, then go to http://YOUR-IP-ADDRESS/books.

bookshelf $ ./script/server

If all goes according to plan you should see some basic HTML!

Ruby on Rails Tutorial: Conclusion

And that is it! You have reached the end of this Ruby on Rails Tutorial and can answer the question, “What is Ruby on Rails?” And now when someone asks “what is a web app?” you can show them yourself!

You now grasp the basics to make virtually any Ruby on Rails web app, and more specifically, how to do it with a SkySilk Turnkey VPS. For more documentation on Ruby on Rails commands and how to develop different specifics check out Ruby’s dedicated support materials site: rubyonrails.org/

If you need any help at all setting up your new Linux Server with Ruby on Rails, feel free to contact us anytime at [email protected].

Deploy a Ruby on Rails VPS

Share this post with your friends