DEV Community

Lisa Jung
Lisa Jung

Posted on

Beginner's guide to creating a new Ruby on Rails application

The time has finally come.

You have been working tirelessly to polish your Ruby programming skills, dreaming about building your very first web application on Rails that will take the world by storm.

You sit down in front of your computer, lay your fingers on your well worn keyboard, only to find yourself thinking "Wait... I have no idea how to get started..."

Having been in that exact predicament this morning, I felt compelled share what I have learned with beginners just like me.

Creating a new Ruby on Rails application is not as daunting as it seems.

This blog will cover how we can create the foundation of Ruby on Rails app for our chocolate shop. This app will help users view all the chocolates that are sold on our website. All of our chocolates have two attributes: classification of chocolate & ingredients in chocolate.

Let's follow these steps to create the foundation of our Ruby on Rails app.

  1. Start a new rails application
  2. Create models
  3. Create and migrate a table to store all instances and records
  4. Seed your data
  5. Create controllers
  6. Set up route
  7. Fire up server to check app functionality

STEP 1: Start a new Rails application

In the directory of your choosing, type the following into your terminal. This command will start a new Rails application named chocolate_addict.

#in your terminal

rails new chocolate_addict --api
Enter fullscreen mode Exit fullscreen mode

Change into chocolate_addict directory and open the app by typing the following into your terminal.

#in your terminal

cd chocolate_addict

code .
Enter fullscreen mode Exit fullscreen mode

In the explorer of your newly created Rails app, you will notice that Rails has endowed our chocolate_addict app with a lot of files. No need to get overwhelmed!

The majority of the files you will be working with will be in the:

  • app directory contains controller & models directories
  • db directory contains seeds.rb
  • config directory contains routes.rb

STEP 2: CREATE MODELS

We are building a simple app that displays all the chocolate in our database in our user's browser.

Therefore, we only need to create one model named chocolate.

To create a model, we will create a file called chocolate.rb under model directory, which falls under app directory. In your terminal, copy and paste the code below.

#in your terminal

touch app/models/chocolate.rb
Enter fullscreen mode Exit fullscreen mode

In your explorer, expand the app directory, then expand the models directory. You will see that a file named chocolate.rb has been created.

Open chocolate.rb file.

Within that file, we will create a model named Chocolate and have the model inherit from ApplicationRecord as shown below.

# in app/models/chocolate.rb

class Chocolate < ApplicationRecord
end 
Enter fullscreen mode Exit fullscreen mode

STEP 3: CREATE AND MIGRATE A TABLE TO STORE ALL INSTANCES AND RECORDS OF MODEL CHOCOLATE

This is done in two step process:
1.Create a migration
2.Migrate

1.To create a migration,use rails generator to create a table. The following is the syntax you will follow to create a table in Rails:

rails g migration CreateTableName attribute_key:datatype
Enter fullscreen mode Exit fullscreen mode

In your terminal, copy and paste the following:

#in your terminal

rails g migration CreateChocolates classification:string ingredient:string
Enter fullscreen mode Exit fullscreen mode

In your explorer, expand the db directory, then expand the migration directory. You will see that a file named 20200421055857_create_chocolates.rb has been created.

** Please note that 20200421055857 seen before create_chocolates.rb is a time stamp. Your's will have a different time stamp as you will create this file at different time and date.

If you open this file, you will see that create_chocolate table has already been created for you with attribute keys and data type you have specified above.

#in db/migrate/20200421055857_create_chocolates.rb

class CreateChocolates < ActiveRecord::Migration[6.0]
  def change
    create_table :chocolates do |t|
      t.string :classification
      t.string :ingredient
    end
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Next step is to migrate. Run this command in the terminal.
#in your terminal

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

If migration was successful, you will see the following message in your terminal.

== 20200421055857 CreateChocolates: migrating =================================
-- create_table(:chocolates)
   -> 0.0023s
== 20200421055857 CreateChocolates: migrated (0.0024s) ========================
Enter fullscreen mode Exit fullscreen mode

In your app explorer, go to the db directory, you will see that a schema.rb file has been created. This file includes the schema of chocolates table we have just created.

#in db/schema.rb
ActiveRecord::Schema.define(version: 2020_04_21_055857) do

  create_table "chocolates", force: :cascade do |t|
    t.string "classification"
    t.string "ingredient"
  end

end
Enter fullscreen mode Exit fullscreen mode

STEP 4: SEED YOUR DATA

We are building a web app that helps users to see all chocolates in our inventory. In order to do that, we need to seed data of all chocolates in our inventory.

In your explorer, go to the db directory and open seeds.rb file.

In your text editor, create instances of chocolates in our inventory.

# in db/seeds.rb

Chocolate.create(classification:"dark", ingredient:"raspberries")
Chocolate.create(classification:"milk", ingredient:"almonds")
Chocolate.create(classification:"white", ingredient:"rose petals")
Chocolate.create(classification:"dark", ingredient:"crystallized ginger")
Enter fullscreen mode Exit fullscreen mode

Seed your database by running the following command in your terminal.

#in your terminal

rails db:seed 
Enter fullscreen mode Exit fullscreen mode

In order to check if seeds are inserted correctly into our database, we will use rails c command in the terminal. Test out some methods like Chocolate.all in the console to see if it pulls up all the instances of our chocolates.

#in your terminal, rails console

rails c

2.6.1 :001 > Chocolate.all
   (0.6ms)  SELECT sqlite_version(*)
  Chocolate Load (0.2ms)  SELECT "chocolates".* FROM "chocolates" LIMIT ?  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Chocolate id: 1, classification: "dark", ingredient: "raspberries">, #<Chocolate id: 2, classification: "milk", ingredient: "almonds">, #<Chocolate id: 3, classification: "white", ingredient: "rose petals">, #<Chocolate id: 4, classification: "dark", ingredient: "crystallized ginger">]> 
2.6.1 :002 > Chocolate.first.ingredient
  Chocolate Load (0.2ms)  SELECT "chocolates".* FROM "chocolates" ORDER BY "chocolates"."id" ASC LIMIT ?  [["LIMIT", 1]]
 => "raspberries" 
Enter fullscreen mode Exit fullscreen mode

If you see the output above, that means our database has been seeded correctly!

STEP 5: CREATE CONTROLLERS

The following is the syntax you will follow to create a controller in Rails:

rails g controller <controller name in plural form>
Enter fullscreen mode Exit fullscreen mode

Copy and paste the following into your terminal.

#in your terminal

rails g controller chocolates
Enter fullscreen mode Exit fullscreen mode

Note that file name and class name for controllers are PLURAL. For controllers, make sure file and class names are pluralized to avoid getting an error message.

In your explorer, under controller directory, you will notice that a new controller file, chocolates_controller.rb, has been created.

In this file, we will write a method that gets called when a user wants to see all the chocolates we have in our inventory by sending a request with the url pattern of "/chocolates".

This is typically done by writing an index action(method) as shown below.

# in app/controllers/chocolates_controller.rb

class ChocolatesController < ApplicationController
    def index
        chocolates = Chocolate.all 
        render json: chocolates
    end
end
Enter fullscreen mode Exit fullscreen mode

The index action(method) is essentially saying "go to the database and get information about all chocolates in our database and send back the info in an HTTP response in JSON format.

STEP 6: SET UP ROUTE
In your explorer, go to config directory and open up routes.rb file.

Routes file determines which controller should handle a specific HTTP request so the appropriate controller can take over and handle that request.

In the routes.rb file, you will see a do end block like this:

# in config/routes.rb
Rails.application.routes.draw do

end
Enter fullscreen mode Exit fullscreen mode

In this block, we need to teach the route to determine which controller is appropriate for handling the type of information being requested.

Use the following syntax to complete the block.

get "/what it's getting",  to: "name of controller#which action/method to call
Enter fullscreen mode Exit fullscreen mode

Copy and paste the following in your routes.rb file.

#in config/routes.rb

Rails.application.routes.draw do
get "/chocolates", to: "chocolates#index"
end
Enter fullscreen mode Exit fullscreen mode

We just established the route so that if this application receives the get request with the url pattern of /chocolates, the route will send this request to the chocolates controller to run the index action.

STEP 7: FIRE UP YOUR SERVER TO CHECK APP FUNCTIONALITY

To fire up your server, copy and paste the following in your terminal.

#in your terminal

rails s
Enter fullscreen mode Exit fullscreen mode

Open up your browser, and type in http://localhost:3000/chocolates.
Our API index,an array with instances of all the chocolates in our inventory should be shown on our browser!

# in your browser

// 20200421065935
// http://localhost:3000/chocolates

[
  {
    "id": 1,
    "classification": "dark",
    "ingredient": "raspberries"
  },
  {
    "id": 2,
    "classification": "milk",
    "ingredient": "almonds"
  },
  {
    "id": 3,
    "classification": "white",
    "ingredient": "rose petals"
  },
  {
    "id": 4,
    "classification": "dark",
    "ingredient": "crystallized ginger"
  }
]
Enter fullscreen mode Exit fullscreen mode

We just created the foundation of our first Ruby on Rails app! Let's recap the steps we have taken to make this happen.

  1. Start a new rails application
  2. Create models
  3. Create a table to store all instances and records
  4. Seed your data
  5. Create controllers
  6. Set up route
  7. Fire up server to check app functionality

Now that we have built the foundation of our app, we can further design and build our app in any way we would like.

Try this on your own to create your app and let me know how it goes!

Top comments (4)

Collapse
 
safventure11000 profile image
Josafe Balili

nice! been looking for this.. rails api implementation.. Thanks :)

Collapse
 
lisahjung profile image
Lisa Jung

You are so welcome! Thank you for the kind words, Saf Venture!

Collapse
 
faizanmustafa profile image
FaizanMustafa

nice and easy to understand guide..

Collapse
 
lisahjung profile image
Lisa Jung

Thanks Faizan!