Creating and Managing Models in Rails

Tutorial 1 of 5

Creating and Managing Models in Rails

1. Introduction

In this tutorial, we will delve into the world of Rails models and learn how to create and manage them effectively. Rails models are an essential component of the MVC (Model-View-Controller) architecture, serving as the primary interface for your application's data.

By the end of this tutorial, you will be able to:

  • Understand what a Rails model is.
  • Create a new model.
  • Define attributes for your model.
  • Perform basic operations on your model.

This tutorial assumes you have Ruby on Rails installed and a basic understanding of the Ruby programming language.

2. Step-by-Step Guide

A model in Rails represents the data in your application. It talks to your database, stores and validates data, performs the business operations.

To create a model, we use the rails generate command. The syntax is rails generate model ModelName.

For instance, if you want to create a model named Book, you would run rails generate model Book.

After running this command, Rails will create several files for you:

  • A migration file to create the books table in your database.
  • A model file in app/models where you will define the behavior of your book objects.
  • A test file for your book model.

In your model file, you can define attributes for your model. For example, a book might have a title and an author.

class Book < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true
end

3. Code Examples

Here's a closer look at the code you'll be working with.

# Generate a model named Book
rails generate model Book title:string author:string

This command creates a migration file to create a books table with title and author columns.

# db/migrate/202108020000_create_books.rb
class CreateBooks < ActiveRecord::Migration[6.0]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author

      t.timestamps
    end
  end
end

Then, you can add validation to your model:

# app/models/book.rb
class Book < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true
end

You can use Rails console (rails console) to interact with your model:

# Create a new book
book = Book.new(title: "The Great Gatsby", author: "F. Scott Fitzgerald")
book.save  # returns true because our book is valid

# Try to create a book without a title
book2 = Book.new(author: "George Orwell")
book2.save  # returns false because our book is invalid

4. Summary

In this tutorial, you learned about Rails models, how to create them and define their attributes, and how to perform basic operations on them.

The next step is to dive deeper into Rails' ActiveRecord, which allows you to interact with your database in an intuitive way.

5. Practice Exercises

  1. Exercise 1: Create a User model with email and password attributes. Make sure the email is unique and both email and password are present.

  2. Exercise 2: Use Rails console to create a new User. Try to create a User with a duplicate email address.

  3. Exercise 3: Modify the User model to include a username attribute. Make sure the username is unique and present.

Solutions:

  1. Run rails generate model User email:string password:string. Modify app/models/user.rb to include validates :email, presence: true, uniqueness: true and validates :password, presence: true.

  2. Use rails console to create a new User. Try to create a User with a duplicate email address. You should get an error.

  3. Generate a migration with rails generate migration AddUsernameToUsers username:string. Run rails db:migrate. Modify app/models/user.rb to include validates :username, presence: true, uniqueness: true.