Ruby: Learning Ruby

A comprehensive Ruby and Rails guide

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Ruby cloud solution that provides a host of benefits, including:

  • Deploy your application in seconds with a simple git push.
  • Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
  • Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
  • Get optimal performance and robust security thanks to a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Ruby cloud hosting solution!

Ruby is a high-level, interpreted programming language designed for simplicity and productivity. Its elegant syntax lets developers accomplish more with less code, while supporting procedural, object-oriented, and functional programming paradigms.

Ruby on Rails, often simply called Rails or RoR, is a robust web application framework written in Ruby. Built on the Model-View-Controller (MVC) pattern, Rails promotes convention over configuration and emphasises the dont repeat yourself (DRY) principle, making it easier and more efficient to build complex web applications.

The Rails command line interface (CLI) is a powerful tool for managing your Rails application. It includes commands for creating new projects, starting the server, accessing the application via the console, and generating various components such as models and controllers. Below are some essential commands every Rails developer should know:

  1. Create a new Rails project:

    rails new project_name
    
  2. Start the Rails server:

    rails server
    
  3. Open the Rails console:

    rails console
    
  4. Generate a new controller:

    rails generate controller controller_name action_name
    
  5. Generate a new model:

    rails generate model ModelName field:type
    
  6. Run database migrations:

    rails db:migrate
    

Routing connects incoming requests to the appropriate controllers and actions in a Rails application. It offers a straightforward way to design URLs and endpoints for your app. Routes are defined in the config/routes.rb file. Here are some common routing patterns:

  1. Root route:

    root 'controller_name#action_name'
    
  2. Generic route:

    get '/path', to: 'controller#action'
    
  3. Resource route (generates standard CRUD routes):

    resources :model_name
    

Controllers serve as the intermediary between models and views by receiving incoming requests and rendering the appropriate responses. The following examples illustrate common controller actions for listing, showing, creating, updating, and deleting resources:

  1. Index action (list all objects):

    def index
      @objects = ModelName.all
    end
    
  2. Show action (display a single object):

    def show
      @object = ModelName.find(params[:id])
    end
    
  3. New action (display form for a new object):

    def new
      @object = ModelName.new
    end
    
  4. Create action (save a new object):

    def create
      @object = ModelName.new(params.require(:model_name).permit(:field1, :field2))
      if @object.save
        redirect_to @object
      else
        render :new
      end
    end
    
  5. Edit action (display form for editing an existing object):

    def edit
      @object = ModelName.find(params[:id])
    end
    
  6. Update action (apply changes to an existing object):

    def update
      @object = ModelName.find(params[:id])
      if @object.update(params.require(:model_name).permit(:field1, :field2))
        redirect_to @object
      else
        render :edit
      end
    end
    
  7. Destroy action (delete an object):

    def destroy
      @object = ModelName.find(params[:id])
      @object.destroy
      redirect_to model_name_path
    end
    

ActiveRecord is Rails' built-in object-relational mapping (ORM) system. It abstracts database interactions and lets you work with database records as native Ruby objects. Here are some common ActiveRecord queries for fetching and manipulating data:

  1. Retrieve all objects:

    ModelName.all
    
  2. Find an object by ID:

    ModelName.find(id)
    
  3. Find an object by a specific field value:

    ModelName.find_by(field: value)
    

Embedded Ruby (ERB) is a templating system that lets you write HTML with Ruby code embedded within. ERB helpers are methods that simplify common tasks in views. Here are a few examples:

  1. Create a link:

    <%= link_to "Link Text", path %>
    
  2. Display error messages:

    <% @object.errors.full_messages.each do |message| %>
      <div><%= message %></div>
    <% end %>
    

Migrations allow you to evolve your database schema in a consistent and verifiable way. They use a Ruby DSL, so you do not have to write raw SQL by hand, making your schema changes database-independent. Here is how you can create and run a migration:

  1. Create a new migration:

    rails generate migration MigrationName
    
  2. In the generated migration file (db/migrate/):

    class MigrationName < ActiveRecord::Migration[6.0]
      def change
        add_column :table_name, :column_name, :type
        remove_column :table_name, :column_name
      end
    end