Building a Shopping Cart in Ruby on Rails (Part 2)

In the previous part I showed you how to create a cart, add products to it and how to keep products in user’s cart so they can leave the session and come back at a later time and their products will still be in their cart. In this part I will show you how to create an order and the admin panel. Let’s get started.

We finished off by creating the view carts/index.html.erb where we create an order.

<div class="total-price"><%= link_to 'Next', 
new_order_path, class: "btn btn-success" %></div>

Order

Obviously, we need a view that will render after clicking “Next” but before we create the view we need to create the model Order first. You can use rails generate model Order, which will also generate the migration and tests for you, but I like to do it manually.

class Order < ApplicationRecord
  belongs_to :cart
  validates :delivery_address, :delivery_type, :payment_type, presence: true

  DELIVERY_TYPES = ["Courier(DPD)", "Personal collection", "InPost"]
  PAYMENT_TYPES  = ["Cash On Delivery", "Bank Transfer", "Dotpay"]
end

delivery_types and payment_types are for the select options in the view.

rails generate migration CreateOrders delivery_address delivery_type payment_type

(Note the “underscore” is missing in delivery_type and payment_type as WordPress does not understand this syntax (sic!)
Note, that rails does not automatically add timestamps for you when using “manual approach” so I added it manually in the migration file.

class CreateOrders < ActiveRecord::Migration[5.0]
  def change
    create_table :orders do |t|
      t.string :delivery_address
      t.string :delivery_type
      t.string :payment_type
      t.timestamps
    end
  end
end

I want to be able to see what products were added to a particular order by a usr so I need to create associations between order, cart and user.

rails generate migration AddUsertoOrders
class AddColumnUsersToOrders < ActiveRecord::Migration[5.0]
  def change
    add_reference :orders, :user, foreign_key: true
  end
end
rails generate migration AddCartToOrders
class AddCartToOrders < ActiveRecord::Migration[5.0]
  def change
    add_reference :orders, :cart, foreign_key: true
  end
end

Now we can create the view.

<% provide(:title, 'Finalize') %>
<% provide(:button_text, 'Create order') %>
<h1>Please enter your details</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
    <%= render 'form' %></div>
</div>

Here I provide the title of the page, a class to the button and render the form, which looks like this:

<%= form_for(@order) do |f| %>
  <% if @order.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
      The form contains <%= pluralize(@order.errors.count, "error") %>.</div>
<ul>
    <% @order.errors.full_messages.each do |msg| %>
<li><%= msg %></li>

<% end %></ul>
</div>

<% end %>
  <%= f.label :delivery_address %>
  <%= f.text_area :delivery_address, rows: 3, cols: 25, class: 'form-control' %>
  <%= f.label :delivery_type %>
  <%= f.select :delivery_type, Order::DELIVERY_TYPES, prompt: 'Select a delivery method', class: 'form-control' %>
  <%= f.label :payment_type %>
  <%= f.select :payment_type, Order::PAYMENT_TYPES, prompt: 'Select a payment method', class: 'form-control' %>
  <%= f.hidden_field :user_id, value: current_user.id %>
  <%= f.hidden_field :cart_id, value: current_cart.id %>
  <%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>

Admin Panel

We want to give admin users the ability to add products, view and manage orders so we add the following to our routes.rb

 namespace :admin do
    resources :products
    resources :orders, only: [:index, :show]
    root 'products#index'
  end

This gives us routes under the path /admin/products and /admin/orders which are directed to Admin::ProductsController and Admin::OrdersController.

Controllers

There are a few things we need to keep in mind for our namespaced controller.

First, Rails expects this controller file to exist in an admin/ folder within app/controllers/ (i.e., at app/controllers/admin/orders_controller.rb).

Second, because the controller is named within the admin namespace, we use the scope resolution operator to define the controller class:

class Admin::OrdersController < ApplicationController
  # Your Methods Here
end

Views

Views that correspond to our Admin::CategoriesController actions are namespaced just like the controller is. When Rails needs these view files, it will look in the app/views/admin/ subfolder.

Additionally, we’ll need to point our path helpers to the right place for namespaced routes. For example, we’ll use paths like new_admin_category_path and form_for [:admin, @category] in our views.

Restricting Access To Admins

There are a couple of approaches here. We’ll start by adding a simple before_action to the Admin::OrdersController:

class Admin::OrdersController < ApplicationController
  before_action :require_admin

  # Your Methods Here

  def require_admin
    unless current_user.admin?
      redirect_to root_path
    end
  end
end

Refactoring

This approach works, but it’s not very flexible. If we add other admin controller and actions (say, for filtering products), we have to redefine this require_admin method in each namespaced controller.

One solution might be to define the require_admin method in our ApplicationController. That’s a step in the right direction, but we would have to remember to add the before_action to each admin controller. These controllers wouldn’t be secure by default.

The solution I prefer is to define a separate class (in app/controllers/) called AdminController that inherits from ApplicationController:

class AdminController < ApplicationController
  before_action :require_admin

  def require_admin
    unless current_user.admin?
      redirect_to root_path
    end
  end
end

Now, each namespaced admin controller can inherit directly (and quite appropriately) from AdminController. Since we’ve defined the before_action in AdminController, actions in any sub-classed controller will be restricted to admin users by default.

We no longer need to list the before_action or define a require_admin method in each of our namespaced controllers; they just inherit from AdminController:

class Admin::OrdersController < AdminController
  # Methods omitted
end

My first Service Objects in Ruby on Rails

I am learning how to keep my controllers clean as they grow while I develop. I am also trying to make my controllers handle only the HHTP-related stuff and move any other logic outside of it to make it read better and optimize it.

As I understand it, a Service Object implements all kind of logics in the controller unrelated to HTTP stuff (params, render, redirect). In fact, services help understand the programmer what the application really does, which is not always obvious when looking at controllers or models. Services have the benefit of extracting the core logic of the application to an isloated object, instead of scattering it around controllers and models.

Let’s see an example. In my application I create reviews for movies. Additional requirements is that the review can have the rating of 0-10 and this can be achieved by skipping the rating in the form for a new review. In order to handle that I need to check if the value of the rating provided in the form in params is blank, if it is I assign the rating of 0 to the review.

class ReviewController < ApplicationController
  ...

  def create
    @review = current_user.reviews.build(review_params)
    @review.movie_id = @movie.id
    @review.user_id = current_user.id

    if params[:review][:rating].blank?
      @review.rating = 0
    end

    if @review.save
      redirect_to movie_path(@movie)
      @review.create_activity :create, owner: current_user
    else
      render 'new'
    end

  end

  ...

end

This method seems rather long. It could be easily refactored, especially the place where I check if the rating is present in params. Let’s refactor this part and make the code a little bit cleaner.

First, we will create a new folder Services in the root folder of our application. Inside it we will create a new file create_review_service.rb. In create_review_service.rb we will create CreateReviewService class. It’s a simple class, it does not inherit from ApplicationController this time because we are isolating everything that happens in the controller
from non-HTTP-related stuff. What we also need is the private method #find_movie that finds the movie we are creating the review for.

class CreateReviewService

  def call(movie_id, attributes, user)
    review = user.reviews.build(attributes)
    movie = Movie.find(movie_id)
    review.movie = movie

    if attributes[:rating].blank?
      review.rating = 0
    end

    review.save
    review
  end

  private
    def find_movie(attributes)
      Movie.find(attributes[:id])
    end
end

Now the controller looks like this:

class ReviewsController < ApplicationController
  ...

  def create
    @review = CreateReviewService.new.call(
      params[:movie_id], review_params,  current_user
    )

    if @review.valid?
      @review.create_activity :create, owner: current_user
      redirect_to movie_path(@movie)
    else
      render 'new'
    end
  end

  ...

end

I create a new object CreateReviewService inside #create method and call #call method on it and pass necessary parameters to the Service Object, where the actual Review is created. Once the Service Object is created, it contains the Review (whether valid or not – validations still work here!) so the only thing that I need to do is to check whether it’s valid.

This code can be refactored further. As you see, after the review is created I create a new activity for a review. This could be a new service.

class CreateActivityForReview
  def call(review, user)
    review.create_activity :create, owner: user
  end
end

I could now create new service object in the controller but I prefer to call it inside of another service – CreateReviewService. Service Object can be called from another Service Object as well.

class CreateReviewService

  def call(movie_id, attributes, user)
    review = user.reviews.build(attributes)
    movie = Movie.find(movie_id)
    review.movie = movie
    if attributes[:rating].blank?
      review.rating = 0
    end
    review.save
    CreateActivityForReview.new.call(review, user)
    review
  end

  private
    def find_movie(attributes)
      Movie.find(attributes[:id])
    end
end

Now, my controller looks like this:

class ReviewController < ApplicationController
  ...
  def create
    @review = CreateReviewService.new.call(params[:movie_id],
    review_params, current_user)
    if @review.valid?
      redirect_to movie_path(@movie)
    else
      render 'new'
    end
  end
end

A book that broadly and comprehensively describes the idea of Service Objects is Fearless Refactoring: Rails controllers by Andrzej Krzywda. It presents numerous real life refactoring examples and techniques. You can see some sample code at http://rails-refactoring.com/. I really recommend reading it, it’s an awesome book. A must read!

Thank you for reading!

Testing Rails Applications

This blog post covers basic concepts of testing Rails applications.
After reading this post, you will know:

  • Why we should write tests
  • Testing ‘philosophies’
  • Types of tests
  • How to write unit and integration tests for your application.

Why do you test it all?

The 4 things that we are looking for in tests are:

  • Catching regressions
  • Feedback
  • Direction
  • Improve the design

Tests will help you catch regressions. If you want your code to continue working as you change it, want to be able to adjust directions rapidly then you should be writing tests. You can catch bugs before they go to production, tests can also provide directions to you while you are developing so writing a simple feature can touch many different pieces in a rails application. Sometimes it’s not really clear what to work on next so a good test can provide you the next missing piece and the links of things you need to write. Doing TDD (Test Development Driven) helps improve the design of the code at a small level. As part of that you get rapid feadback so not just like improving the design but also, for example, as you are writing a class you are thinking about “what do I want to name this method? What should the arguments look like?” It can be really hard to start with that blank piece of paper and so if you are adding tests it’s much easier to figure out the code you want to write bit by bit.

4 Testing ‘philosophies’

  • No testing at all
  • Verification Testing
  • Test First
  • Test Driven Development

The first one is not really a philosophy, you just don’t write any tests.
The next step is where you write code and then write tests that “wrap around” your code.
‘Test First’ is where you write a test, it’s a failing test, we write enough code to make the code pass and then we reflect to see if we need to refactor that code. Lastly, there is ‘Test Driven Development’, this is where your tests define the behiour or almost the design of your application and that defines how your application gets developed or crafted.

What is Unit Testing?

When we say Unit Testing we are talking about testing pieces of our application in isolation from the rest of the application. You end up with lots of individual unit tests so when any one piece breaks you are going to know exactly how to fix it hopefully, which makes your application a lot easier to debug. Also, a lot of people think that good unit test lead to good documentation. If you look at somebody else’s code base and need to know how it works – well, looking at the tests might give you a good hint.

Let’s look at a bsic file structure of a unit test.
Our name of the file is probably going to be the subject we want to test, like:

<subject>_test.rb

The default test stub in test/models/movie_test.rb looks like this:

require 'test_helper'

class MovieTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end

Inside that file you requrie ‘test_helper’. By requiring this file, the default configuration to run our tests is loaded. We are going to include this with all the tests we write, so any methods added to this file are available to all our tests.
Inside the test we declare the Test class which inherits from ActiveSupport::TestCase.

class MovieTest < ActiveSupport::TestCase
end

Any method defined within a class inherited from Minitest::Test (which is the superclass of ActiveSupport::TestCase) that begins with test_ (case sensitive) is simply called a test.
We then can write a bunch of methods, which are each of our tests. Inside the method, the basic building block is going to be a assertion – something that we assert to be true or assert to match. Each test has typically one assertion. Let’s take a look at an example.

Let’s assume we have a Movie model which looks like this:

class Movie < ApplicationRecord
  belongs_to :user
  belongs_to :category
  has_many :reviews, dependent: :destroy
end

It’s a simple ActiveRecord model, that belongs to a user and a category and can have many reviews. In our test we would like to assert that a movie without a title is invalid so we are going to write a test that catches situations when the title is not provided to the movie.

require 'test_helper'

class MovieTest < ActiveSupport::TestCase
  test "invalid without a title" do
    m = Movie.new(title: nil)
    assert_not m.valid?, "Title is not being validated"
  end
end

We define a class with a test in it and we create a new movie without a title. Next, we use one of the assertions to check if the movie is valid or not. We optionaly give it a descriptive message in case the test fails so we know exactly where the problem is. Let’s run the test:

rake test test/model/movie_test.rb

Our test is fails with a message  ‘Title is not being validated’. It fails simply because we haven’t defined any validations on our model yet so let’s do that now.

class Movie < ApplicationRecord
  belongs_to :user
  belongs_to :category
  has_many :reviews, dependent: :destroy
  validates :title, length: { maximum: 45,
    too_long: "%{count} characters is the maximum allowed" }, presence: true
end

Here we specify that a movie needs to have a title and the title cannot be longer than 45 characters. If it’s too long, we will use Rails’es built-in feature to display an error message. Running our test again:

rake test test/model/movie_test.rb

The test passes. Yay!

Did you know?

Rails adds a #test method that takes a test name and a block. It generates a normal Minitest::Unit test with method names prefixed with test so you don’t have to worry about naming the methods, and you can write something like:

test "test the truth" do
  assert true
end

Which is the same as writing this:

def test_the_truth
  assert true
end

You can still use regular method definitions though.

What are Integration Tests?

In this phase of testing, individual modules are combined and tested as a group.
Let’s assume a typical user test case: adding a movie on our website. The business requirement is that a movie can be added only by users that are logged in so a simple step would be to fill out a standard login form. After logging in, the user is displayed a form to create a new movie, the user fills in the required fields, clicks “Create” button and the movie is created. How do we actualy test such scenario?

The idea is that we know what steps you can perform on our website in order to achieve desired effects. We also know that the user is using our website, which is built with HTML elements. Through interaction with it by performing certian activities we know that the HTML changes its structure. We can therefore assume that changing the structure of the HTML is an answer to the interaction with our website, in other words, we can create a test, in which we will look at the HTML and observe whether in our assumed scenario, individual user interactions will create certain HTML structure. In simple words, it’s a user simulation scenario. Let’s jump into an example test case.

We are going to use Rspec and Capybara, which are great tools for writing integration tests.

require 'rails_helper'

describe 'Non-logged in user cannot add a new movie' do
  it 'asks the user to log in first' do
    visit root_path
    visit new_movie_path
    expect(page).to have_content 'You need to sign in or sign up before continuing.'
  end
end

Here we visit the main page, then we go to add a new movie and the expected behaviour of our application is to prompt the user to log in.

As an integration test this is fairly a high level, it operates mostly by going through the web UI. You can see how this would catch regressions because if we do a little refactoring and move things around and suddenly the form does not show up on the page then we will catch that. It will provide direction because as you are implementing this test it will tell you what is missing next so you will see errors like “I don’t have this template”, “I don’t have this controller” vs, say, you are writing a controller test and as soon as the controller is completed then you are all green and everything is good. You’re done.

Let’s sum up

Thinking back again on the benefits of testing – number one: catching regressions and errors will tell you where you have an error while you develop. Number two: it will give you feedback after, say, you’ve added associations. Number three: it will provide you with direction from a high-level – in the test it’s pretty obvious where the problem is.

I hope this gives you an overview of testing rails applications. Till the next one.

Building a Shopping Cart in Ruby on Rails (Part 1)

On my Ruby on Rails course I was tasked to build an e-commerce web application. In this post, I’ll cover creating a shopping cart that will keep track of products and their quantity and allow users to remove items. The full list of requirements was this:

  • display a list of products to the client
  • client can add any product to cart
  • the cart can contain many products
  • the client can remove stuff from the cart
  • at the end, the client can “confirm” the cart, which clears the cart
  • when a client starts adding stuff to the cart, they can come back a day later and still see their cart
  • as for now, the “confirm” feature doesn’t need to do anything – in the next phase, we’ll make it an order, but for now it’s not needed
I’ll try to give you an outline of everything you need to make a robust shopping cart for your web application.
You need at least four models for an e-commerce site: Products, Carts, Orders and Cart Items (which is a join table between products and carts).

Creating and Retrieving the cart

Because a client should be able add products to the cart and have his products in his cart even after he leaves and comes back later we need a way to figure out whether he already has a cart or not. You can create a private method where you retrieve the right cart object based on the cart ID stored in the session, or create the cart if it doesn’t yet exist and store it in the session.
zrzut-ekranu-z-2017-02-05-130331
Because we need to handle this right after the user enters the web site a great place to set this functionality is in the Application Controller.
You also need to make sure to handle an exception when a cart cannot be retrieved from the database for some reason and rescue ActiveRecord::RecordNotFound and create a new one.
You may wonder, what happens when a customer creates a cart but then abandons it? Well, you may use it as a good source of information, for example to check what products are added the most, which shows what products interest the clients the most. On the other hand, you may not want to destroy the carts, especially if you add users later on and associate carts with users.

Adding products to cart

In order to add products to the cart we need the actual cart. You can use your set_cart method that you’ve just defined in your Application Controller then you can use a before_action filter to specify which actions need to retrieve or create a cart.
zrzut-ekranu-z-2017-02-05-135417
You probably noticed the add_product method on cart. This is a special method we create on the cart model that allows us to create initial Cart Items records, as well as keep track of the quantity of the same product. If we simply used @cart.ordered_items.build, we’d be creating individual records of the same product each time.
Let’s take a look at add_product method:
zrzut-ekranu-z-2017-02-05-132603

Instead of creating a separate record of the same product each at a time users can choose the quantity of items they want to add. So a quantity parameter is always being passed to the controller action inside of product_params.

So what happens is add_product checks for the existence of the Cart Item record in the cart. If  you have the same product in your cart, it simply updates the quantity and saves the record. Otherwise, you create the relationship and return the item.

Adding and removing products

Like most e-commerce sites, we’ve built a page where customers can look at their cart and update the quantity of items or remove them entirely. This calls for one more action in our Cart Items controller: destroy:zrzut-ekranu-z-2017-02-05-134047

Now we have everything we need to keep track of products in a customer’s cart.

In my next post, I’ll cover user authentication, how to handle check out and processing orders as well as admin panel where an admin can add/manage products and prices, see existing orders and see reports of selling products in the last 30 days.

Find and collect maps, select, inject and zip them – useful Ruby methods

Today I would like to share with you some methods I have learned in Ruby. They are very cool and help a lot in resolving complex problems.

#map and #map!

#map and #map! transform elements of an array.

zrzut-ekranu-z-2016-12-17-202151

In my example, it iterates over each element of my_array and multiplies it by 2 and returns a new array with transformed data. It did not change my existing array. I can override my existing array with transformed data by using #map!

zrzut-ekranu-z-2016-12-17-202259

# NOTE: ‘collect’ is another name for the ‘map’ operation.


#select

#select finds elements of an array that match certain criteria. For example:

zrzut-ekranu-z-2016-12-17-201607

On above screen shot it finds all even numbers from array.

# NOTE: ‘find_all’ is another name for the ‘select’ operation.


#find

#find locates the first element matching a criteria.

zrzut-ekranu-z-2016-12-17-203738


#inject

#inject is useful when performing complex mathematical operations like 68 + 98 + 32+ 132… To solve this the ‘each’ method could be used:

zrzut-ekranu-z-2016-12-17-204942

That took 5 lines of code which really seems like a waste! Let’s rewrite this by calling #inject:

zrzut-ekranu-z-2016-12-17-205730

From 5 lines of code we narrowed it down to just 1! Nice! And there is even better way of writing it:

zrzut-ekranu-z-2016-12-17-210015

Really mind-blowing 🙂


#zip

The ‘zip’ method is implemented in the Array class and Enumberable module and is useful for combining collections in an ordered way. A trivial example:

zrzut-ekranu-z-2016-12-17-211931

It iterates over each of the collections, collecting one element from each and returning an ordered collected array of arrays.


Now, some methods mentioned above together in action. They helped me solve Hamming Distance exercise (check it out here).

zrzut-ekranu-z-2016-12-17-211420

 

Unveiling ‘magick’ of Ruby on Rails validations

Today I learned something really usefull. I learned that validations of models in Ruby on Rails is no ‘magick’, as I used to think. Thanks to Andrzej Krzywda from Arkency I learned how this all works and where this all comes from.

First, I visited rails’es github and took a look at the actual rails implementation of #validates method here. Next, I tried seeing it in action by creating a simple app and using #validate method in my model.

I have a simple model Message, which has a title and content field. I have commented out #validate method for now just to show you how it works.

class Message < ApplicationRecord
  #validates :title, presence: true
end

I will now try to create a new message:

rails console
message = Message.new
=> #<Message id: nil, title: nil, content: nil, created_at: nil, updated_at: nil,>

As you can see I have a message without a title, without content and created_at fields, which basically means I have an invalid mesasge. If I now call #valid? method on the message I will still get ‘true’.

message.valid?
=> true

Hmm, that’s not good.
I will now uncomment the #validate method in my model:

class Message < ApplicationRecord
  validates :title, presence: true
end

and call #valid? on my message:

message.valid?
=> false

Bingo! That’s how Rails protect me from having invalid messages in my database. Awesome!

I can also see why my message is invalid by calling #errors on my message:

message.errors
#<ActiveModel::Errors:0x0000000638ddc0 @base=#<Message id: nil, title: nil, @messages={:title=>["can't be blank"]...>

It says “title can’t be blank”. The output is not very readable so let’s extract #full_messages from the errors:

message.errors.full_messages
 => ["Title can't be blank"]

We get an array of exact error messages. Great!
So let’s actually show the error messages in the browser.

<%= form_for(message) do |m| %>
  <% if message.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(message.errors.count, "error") %> prohibited this ride from being saved:</h2>
      <ul>
      <% message.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

It actually comes in every scaffold out of the box.
If I now try to create a new message and hit ‘Create’ I will get an error:

1 error prohibited this message from being saved:

  • Title can’t be blank

So what it does is when it encounters any errors it creates a ‘div’ element with a class ‘error_explanation’ and appends #errors.full_messages to it.
There are many, many other useful options of validations, you can check them out on Ruby Guides
Thanx!

How to deploy a Rails app to Heroku?

I started off the first week by creating a simple ‘Hello World’ application and deploying it to Git. Another thing I wanted to learn was to deploy an application to production so everyone can actually see it in the itnernet. I wanted to learn how to deploy an application to Heroku.

I created a simple blog.

rails new blog

Since I already knew that Heroku uses Postgresql database by default I knew I had to update my Gemfile to provide postgresql library for Heroku. Here’s how my Gemfile looks:

group :development, :test do
  gem 'sqlite3'
end

group :production do
  gem 'pg', '~> 0.19.0'
end

I moved ‘sqlite3’ to development and test environment and created a separate group for production where I put gem ‘pg’, ‘~> 0.19.0’, which is the latest version of postgresql library now.

I tried to ‘bundle’ my gems but I got an error message saying ‘Make sure “gem install ‘pg’, ‘~> 0.19.0’ runs successfully.”‘ It took me some time to figure out what was wrong and finally I came across a hint on Stackoverflow that said that I needed to have Postgresql installed on my local computer. What I also found out was that if I don’t have it installed I can just run ‘bundle –without production’ which will bundle only the gems for development and test environment and skipp production.

I actually wanted to try both ways. I ran ‘bundle –without prodcution’ and it all went fine. I then installed Postgresql by running ‘sudo apt-get install postgresql’ and tried it but I got same error message as before. Something was still wrong. I did another search in Stackoverflow and found out that I needed to install ‘libpq-dev’ package which is a ‘library for compiling C programs to link with the libpq library in order to communicate with a PostgreSQL database backend’ (https://packages.debian.org/pl/sid/libpq-dev). I installed it and tried to ‘bundle’ again and it worked fine this time.

I wanted to have basic CRUD options and a database in my blog so I generated a simple scaffold:

rails generate scaffold Post title:string content:text

Then I ran migration:

rails db:migrate

I created some demo posts to populate the database with some data and I was ready to creat a new repository to commit the changes:

cd blog
git init
git commit -am "Add new blog application"

I knew I had to interact with Heroku somehow so I knew I needed some kind of an interface to communicate with the server so I searched for documentation in the internet and found a prety decent instructions at Heroku (toolbelt.heroku.com) which helped me install Heroku client with a snap of a finger!

wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh

Next I tried to log in to Heroku localy to create an appilcation

heroku login

but I got an error message saying that Heroku could not verify my identity becasue it didn’t have a valid key. No problem:

heroku add:keys

Try it again:

heroku login

Login successfull!

Now I created a new application:

heroku create jedrekblog

Just to verify it all worked fine I logged in via http://www.heroku.com to my account and double-checked that my new application was there. Yup, it’s there! I can see it!

Finally:

git push heroku master

Yay! I can now go to https://jedrekblog.herokuapp.com/ address. Awesome!

‘Err…What on earth is going on? Why is it not working?’, I was thinking for a while. It didn’t work. ‘Something went wrong’, it said. ‘Not very much’, I thought so I needed to know what exactly happened. I found a simple way of troubleshooting the issue by reading logs.

heroku logs

‘500 Internal Server Error’, it said. ‘Database does not exist’. Hmm….

After some research in the internet I learned that Heroku does not migrate database from the local computet so I had to migrate it to production.

heroku run rake db:migrate

Let’s give it a try now. Yay! It works!

And that’s it.
So deplying a Rails application to Heroku is not a difficult task but it requires some investigation and research.

I’ve gathered together the key steps below:

wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh
heroku keys:add
rails new blog
group :development, :test do
  gem 'sqlite3'
end

group :production do
  gem 'pg', '~> 0.19.0'
end
bundle --without production
rails generate Scaffold Post title:string content:text
rails db:migrate
git init
git commit -am "Add new application"
heroku login
heroku create NameOfYourApp
git push heroku master
heroku run rake db:migrate

That’s it! Thanx!