# Model

The model, resource, and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want, then statements for adding these columns will also be created. For example, running:

bin/rails generate model Product name:string description:text
1

This will create a Productmodel and migration, mapped to a productstable at the database.

class Product < ApplicationRecord
end
1
2

migration looks like:

class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
1
2
3
4
5
6
7
8
9
10
  • Table Name

    After glancing at the example above, you may have noticed that we did not tell Eloquent which database table corresponds to our Product model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified.

    If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining a **table_name**property on the model:

    class Product < ApplicationRecord
      self.table_name = "my_products"
    end
    
    1
    2
    3

    If you do so, you will have to define manually the class name that is hosting the fixtures (my_products.yml) using the set_fixture_class method in your test definition:

    class ProductTest < ActiveSupport::TestCase
      set_fixture_class my_products: Product
      fixtures :my_products
      # ...
    end
    
    1
    2
    3
    4
    5

    It's also possible to override the column that should be used as the table's primary key using the ActiveRecord::Base.primary_key=method:

    class Product < ApplicationRecord
      self.primary_key = "product_id"
    end
    
    1
    2
    3

    Active Record does not support using non-primary key columns named id.

  • Create

    Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The newmethod will return a new object while createwill return the object and save it to the database.

    #create
    user = User.create(name: "David", occupation: "Code Artist")
    
    #new
    user = User.new
    user.name = "David"
    user.occupation = "Code Artist"
    
    1
    2
    3
    4
    5
    6
    7
  • Read

    Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.

    # return a collection with all users
    users = User.all
    
    1
    2
    # return the first user
    user = User.first
    
    1
    2
    # return the first user named David
    david = User.find_by(name: 'David')
    
    1
    2
    # find all users named David who are Code Artists and sort by created_at in reverse chronological order
    users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)
    
    1
    2
  • Update

    Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.

    user = User.find_by(name: 'David')
    user.name = 'Dave'
    user.save
    
    1
    2
    3

    A shorthand for this is to use a hash mapping attribute names to the desired value, like so:

    user = User.find_by(name: 'David')
    user.update(name: 'Dave')
    
    1
    2

    This is most useful when updating several attributes at once. If, on the other hand, you'd like to update several records in bulk, you may find the update_allclass method useful:

    User.update_all "max_login_attempts = 3, must_change_password = 'true'"
    
    1

    This is the same as if you wrote:

    User.update(:all, max_login_attempts: 3, must_change_password: true)
    
    1
  • Delete

    Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.

    user = User.find_by(name: 'David')
    user.destroy
    
    1
    2

    If you'd like to delete several records in bulk, you may use  destroy_by  or  destroy_all  method:

    # find and delete all users named David
    User.destroy_by(name: 'David')
    
    # delete all users
    User.destroy_all
    
    1
    2
    3
    4
    5