Your blog can show a page, but it cannot remember anything yet. In this lesson you give it a database. You will create Article and Comment models, change the database with migrations, protect your data with validations, connect the two models with associations, and use the Rails console to create and query records. This is the foundation every later lesson builds on.
What you'll learn
- What Active Record is and which naming conventions it follows
- How to generate a model and run a migration
- How to experiment with your data in the Rails console
- How to validate data before it is saved
- How to connect models with
has_manyandbelongs_to - How to write common queries and reusable scopes
What is Active Record?
Active Record is the part of Rails that talks to your database. It is an ORM (object-relational mapper): each database table maps to a Ruby class, each row to an object, and each column to an attribute on that object.
Active Record relies on conventions so you do not have to configure anything:
- The model
Article(singular, CamelCase) maps to the tablearticles(plural, snake_case). - Every table gets an
idprimary key automatically. - The columns
created_atandupdated_atare filled in for you. - A column called
article_idis a foreign key pointing to thearticlestable.
Generating the Article model
From your blog folder, run:
bin/rails generate model Article title:string body:text published:booleanThe arguments after the model name are column names and types. Common types are string (short text), text (long text), integer, decimal, boolean, date, datetime and references (a foreign key).
The generator creates several files. The two most important are the model and a migration:
class Article < ApplicationRecord
endThe model is empty, yet it already knows about every column in the articles table. Active Record reads the columns from the database when the app runs.
Migrations
A migration is a Ruby file that describes a change to your database schema. Migrations are versioned with a timestamp in the filename, so every developer on a team and every server applies the same changes in the same order. Open the new file in db/migrate/:
class CreateArticles < ActiveRecord::Migration[8.1]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.boolean :published
t.timestamps
end
end
endThe number in brackets matches your Rails version, so you may see 8.0 instead. t.timestamps adds the created_at and updated_at columns.
Before running it, improve it. An article should be a draft until you publish it, so give published a default value and forbid NULL:
t.boolean :published, default: false, null: falseNow apply the migration:
bin/rails db:migrateRails creates the table in your SQLite database (in storage/development.sqlite3) and updates db/schema.rb, a snapshot of your current database structure. You never edit schema.rb by hand; it is regenerated every time you migrate.
The Rails console
The Rails console is an interactive Ruby session with your whole app loaded. It is the best place to explore models. Start it with:
bin/rails consoleNow create your first article:
article = Article.new(title: "Hello Rails", body: "My very first post.")
article.new_record? # => true
article.save # => true
article.id # => 1
article.published # => false (the default from the migration)new builds an object in memory and save writes it to the database. create does both in one step:
Article.create(title: "Second post", body: "Rails is fun.", published: true)Reading, updating and deleting are just as short:
Article.count # => 2
Article.first # the oldest article by id
Article.find(1) # find by id, raises an error if missing
Article.find_by(title: "Second post") # first match, or nil
article = Article.find(1)
article.update(published: true) # changes and saves in one call
article.destroy # deletes the rowWatch the console output: Active Record prints the SQL it runs for each command. Reading that SQL is a great way to learn what your Ruby code really does.
Validations
Right now you can save an article without a title, which makes no sense for a blog. Validations check data before it reaches the database:
class Article < ApplicationRecord
validates :title, presence: true, length: { maximum: 120 }
validates :body, presence: true
endTry it in the console (run reload! first if it is still open):
article = Article.new(title: "")
article.valid? # => false
article.save # => false, nothing is written
article.errors.full_messages
# => ["Title can't be blank", "Body can't be blank"]save and create return false (or an unsaved object) when validation fails. Their "bang" versions, save! and create!, raise an exception instead. Use the bang versions in scripts and seeds where a failure should stop everything; use the normal versions in controllers, where you want to show the errors to the user. You will do exactly that in the next lesson.
Other built-in validations you will use often include uniqueness, numericality, inclusion and format.
Comments and associations
A blog post can have many comments, and each comment belongs to one article. Generate the Comment model with a references column:
bin/rails generate model Comment article:references author:string body:text
bin/rails db:migrateThe references type creates an article_id column with an index and a foreign key constraint, so the database itself refuses comments that point to a missing article. The generator also adds the association to the model:
class Comment < ApplicationRecord
belongs_to :article
validates :author, presence: true
validates :body, presence: true, length: { maximum: 1000 }
endAdd the other side of the relationship to Article:
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { maximum: 120 }
validates :body, presence: true
enddependent: :destroy means that when you delete an article, its comments are deleted too. Without it, the foreign key would block the deletion.
Associations give you convenient methods in both directions:
article = Article.create!(title: "Associations", body: "Let's connect models.")
comment = article.comments.create!(author: "Aisha", body: "Great explanation!")
comment.article # => the article
article.comments.count # => 1
article.comments.first.author # => "Aisha"Calling article.comments.create! sets article_id for you. Note that belongs_to is required by default: a comment without an article is invalid.
Querying your data
Active Record has a chainable query interface. Here are the methods you will reach for every day:
Article.where(published: true) # all published articles
Article.where(published: false).count # number of drafts
Article.order(created_at: :desc) # newest first
Article.where(published: true).order(created_at: :desc).limit(5)
Article.where("title LIKE ?", "%Rails%") # SQL fragment with a safe placeholder
Article.pluck(:title) # an array of titles only
Article.exists?(title: "Hello Rails") # true or falseThese methods return an ActiveRecord::Relation, not an array. A relation is lazy: no SQL runs until you actually need the records, for example when you loop over them or call count. That is why you can keep chaining. To see the SQL a relation would run, call to_sql on it:
Article.where(published: true).order(created_at: :desc).to_sqlWhen you use the same condition in many places, give it a name with a scope:
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { maximum: 120 }
validates :body, presence: true
scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }
endNow your queries read like plain English: Article.published.recent.limit(5).
Always pass user input to where as a hash or with ? placeholders, never by building SQL strings with interpolation. Placeholders protect you from SQL injection.
Seed data
Typing records into the console gets old quickly. Put sample data in db/seeds.rb:
Comment.destroy_all
Article.destroy_all
welcome = Article.create!(
title: "Welcome to the blog",
body: "This is the first published article.",
published: true
)
welcome.comments.create!(author: "Sam", body: "Looking forward to more posts.")
Article.create!(
title: "A draft in progress",
body: "This article is not published yet."
)Load it with:
bin/rails db:seedBecause the file deletes existing records first, you can run it as often as you like to reset your development data.
Esercizio
Practice queries in the console
- Run
bin/rails db:seed, then openbin/rails console. - Create two more published articles, each with at least two comments, using
article.comments.create!. - Try to create a comment with an empty author. What does
errors.full_messagessay? - Write queries that return:
- the titles of all published articles, newest first
- the number of comments on the welcome article
- all drafts
- Delete one article with
destroyand confirm withComment.countthat its comments were deleted too.
Check your understanding
Verifica rapida
What does running bin/rails db:migrate do?
Verifica rapida
An Article has_many comments with dependent: :destroy. What happens when you call destroy on an article?
Summary
- Active Record maps tables to classes and rows to objects, following naming conventions.
bin/rails generate modelcreates a model and a migration;bin/rails db:migrateapplies it and updatesdb/schema.rb.- The Rails console is your playground for creating, reading, updating and deleting records.
- Validations such as
presenceandlengthkeep bad data out; checkerrors.full_messageswhen a save fails. has_manyandbelongs_toconnect models;dependent: :destroycleans up related records.- Queries like
where,orderandlimitare lazy and chainable, and scopes give them reusable names.
In the next lesson you will put your models on the web with routes, controllers and views, so visitors can read articles and leave comments.