Creating a model in Ruby On Rails

Create a model in Ruby on Rails with an example: learn how to use the ActiveRecord ORM to quickly and easily create models and manipulate data.

Creating a Model in Ruby On Rails

A model is a class that inherits from the ActiveRecord::Base class. Models are used to represent tables in a database, and provide an interface for creating, retrieving, updating, and deleting records. Models are usually defined in the app/models directory in a Rails application.

To create a model, we use the rails generate command. Let's create a model for a table called "users":

$ rails generate model User
      invoke  active_record
      create    db/migrate/20160519085959_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb

This command creates a migration file, which is used to create the database table. It also creates a model file, which is used to define the model. Finally, it creates a model spec file, which is used to write tests for the model.

The migration file looks like this:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end

This migration creates a database table called "users" with two columns, "name" and "email". It also adds two columns, "created_at" and "updated_at", which are used to track when the record was created and updated.

The model file looks like this:

class User < ActiveRecord::Base
  validates :name, presence: true
  validates :email, presence: true, uniqueness: true
end

This model is used to validate the data that is saved in the database. In this example, the model ensures that the "name" and "email" fields are present, and that the "email" field is unique.

Finally, the model spec file looks like this:

require 'rails_helper'

RSpec.describe User, type: :model do
  it { should validate_presence_of(:name) }
  it { should validate_presence_of(:email) }
  it { should validate_uniqueness_of(:email) }
end

This spec file tests the model to ensure that it validates the data correctly. It tests that the presence validations are working correctly, and that the uniqueness validation is working correctly.

Once the model is created, it can be used in the application to create, retrieve, update, and delete records from the database.

Answers (0)