3 min read

Ruby on Rails: A Beginner's Guide

Ruby on Rails is a powerful framework for building web applications. By following these lessons, you've learned how to create a new Rails application, set up controllers and models, work with the database, and implement relationships between data.
Ruby on Rails: A Beginner's Guide

Ruby on Rails (often referred to as Rails) is a powerful web application framework built on the Ruby programming language. Rails provides a set of conventions and tools for developers to rapidly create robust web applications.

Lesson 1: Introduction to Ruby on Rails

To get started with Rails, you’ll first need to install Ruby and Rails on your machine. Once you have that set up, you can create your first Rails application with the following commands:

  1. Create a new Rails project: rails new MySite
  2. Install required gems: bundle install
  3. Start the Rails server: rails server
    You can now access your app by navigating to http://localhost:8000 in your browser.
  4. Generate a controller: rails generate controller Pages
  5. Start a Rails server on a specific port: rails s -p 8000
  6. Generate a model: rails generate model Message content:string
  7. Run migrations: bundle exec rake db:migrate
  8. Seed your database: bundle exec rake db:seed
  9. Clean assets: Rails assets:clean
  10. Precompile assets: Rails assets:precompile

Understanding the Rails Request/Response Cycle

When you enter the URL http://localhost:8000 in your browser, the following happens:

  1. The browser sends an HTTP request to your application.
  2. The request hits the Rails router (found in config/routes.rb).
  3. The router identifies the appropriate controller and action.
  4. The controller processes the request and fetches necessary data.
  5. The controller passes data to a view.
  6. The view renders the response in HTML format and sends it back to the browser.

Routing in Rails

The routes in Rails are defined in config/routes.rb. To set up a root route (the page users see first), add this line:

root 'pages#home'

You can define other routes to map to specific controller actions:

get 'welcome' => 'pages#home'

Rails makes it easy to add named routes and manage resources. You can use the resources keyword to automatically create routes for the seven standard controller actions: index, show, new, create, edit, update, and destroy.

resources :messages

Lesson 2: Saving Data in Rails

Rails uses controllers to handle requests and models to manage data. Here's how you can handle the Message model in a controller:

class MessagesController < ApplicationController
  def index
    @messages = Message.all
  end

  def new
    @message = Message.new
  end

  def create
    @message = Message.new(message_params)
    if @message.save
      redirect_to '/messages'
    else
      render 'new'
    end
  end

  private

  def message_params
    params.require(:message).permit(:content)
  end
end

This controller handles displaying messages, creating new messages, and saving them to the database.

In the view (index.html.erb), you can display the saved messages:

<div class="messages">
  <div class="container">
    <% @messages.each do |message| %>
      <div class="message">
        <p class="content"><%= message.content %></p>
        <p class="time"><%= message.created_at %></p>
      </div>
    <% end %>
    <%= link_to 'New Message', "messages/new" %>
  </div>
</div>

Lesson 3: Models in Rails

In Rails, models are representations of database tables. A model is defined as a Ruby class, and it contains business logic and data manipulation methods. Here's an example of a Tag model:

class Tag < ActiveRecord::Base
  has_many :destinations
end

And the Destination model:

class Destination < ActiveRecord::Base
  belongs_to :tag
end

The has_many association means a tag can have multiple destinations, while the belongs_to association means each destination is linked to a single tag.

Lesson 4: Advanced Models and Relationships

Rails supports advanced model relationships, such as many-to-many associations. Here's how you might define a many-to-many relationship between Tag and Destination:

class Tag < ActiveRecord::Base
  has_many :destinations
end

class Destination < ActiveRecord::Base
  belongs_to :tag
end

To handle editing a destination:

class DestinationsController < ApplicationController
  def show
    @destination = Destination.find(params[:id])
  end

  def edit
    @destination = Destination.find(params[:id])
  end

  def update
    @destination = Destination.find(params[:id])
    if @destination.update(destination_params)
      redirect_to(:action => 'show', :id => @destination.id)
    else
      render 'edit'
    end
  end

  private

  def destination_params
    params.require(:destination).permit(:name, :description)
  end
end

Seed Data Example

Rails also allows you to populate your database with initial data using db:seed. Here's an example:

b1 = Book.create(title: "American Sniper", author: "Chris Kyle", description: "A Navy SEAL sniper's memoir.", publisher: "Morrow", weeks_on_list: 63, rank_this_week: 1)
b2 = Book.create(title: "Unbroken", author: "Laura Hillenbrand", description: "The survival story of an Olympic athlete during WWII.", publisher: "Random House", weeks_on_list: 25, rank_this_week: 2)

This data is inserted into your database when you run:

bundle exec rake db:seed

Conclusion

Ruby on Rails is a powerful framework for building web applications. By following these lessons, you've learned how to create a new Rails application, set up controllers and models, work with the database, and implement relationships between data. Keep experimenting, and you'll be able to build more complex and dynamic web apps in no time!