The M in MVC: Active Record
Lesson 56 left out the model – the data. In Rails that is Active Record: one class per table, one object per row, and the SQL is written for you. (The name is the pattern's, from Martin Fowler's book: an object that carries its database row around with it.) Active Record works outside Rails too – here on its own, with SQLite in the page as in lesson 78, where Sequel did the same job in its own style.
First the table. On your computer a migration file creates it; the schema block below is the same code, run right away. The log under the cell shows the SQL Active Record writes:
install_gem "rails"
require "active_record"
ActiveRecord::Base.logger = Logger.new(STDOUT) # the SQL, under each cell
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "diner.db")
ActiveRecord::Schema.define do
create_table :dishes, force: true do |t|
t.string :name
t.decimal :price, precision: 6, scale: 2
t.timestamps
end
end
ActiveRecord::Base.connection.tablescreate_table :dishes with t.string, t.decimal and t.timestamps – two columns, created_at and updated_at, that Active Record fills in by itself; id comes for free. force: true drops the table first, so the cell can run again. The two extra tables are Rails' own bookkeeping: which migrations ran. diner.db is a real SQLite database – below the cell it is offered as a download.
Now the class. Its name is singular, the table's plural – Active Record knows that Dish goes with dishes (convention over configuration again), and the columns become attributes without a line of code:
class Dish < ActiveRecord::Base
validates :name, presence: true
end
Dish.delete_all # a clean table whenever this cell runs again
Dish.create!(name: "Bacon", price: 4.5)
Dish.create!(name: "Egg", price: 2)
Dish.create!(name: "Coffee", price: 3.2)
Dish.countDish.create! is Dish.new(…) plus save!: the log shows each INSERT in a transaction of its own, and RETURNING "id" brings the new id back. validates :name, presence: true is a validation: a dish without a name is not saved – save answers false and errors explains why, while save! and create! raise. Asking questions is where Active Record shines: where, order and the rest return a relation that becomes SQL only when the rows are needed, so they chain:
cheap = Dish.where("price < ?", 4).order(:price)
puts cheap.to_sql
puts cheap.map(&:name).inspect
egg = Dish.find_by(name: "Egg")
egg.update!(price: 2.5)
puts egg.updated_at
nameless = Dish.new(price: 1)
puts nameless.save
nameless.errors.full_messagesThe ? in where("price < ?", 4) is a placeholder: the value is passed to the database separately, never glued into the SQL – the one habit that keeps SQL injection out. find_by returns one object or nil, update! writes an UPDATE and sets updated_at – and the dish without a name stays out, with a message a form could show.
bin/rails generate model Dish name:string price:decimal writes the model class and a migration file, bin/rails db:migrate creates the table, and bin/rails console is an IRB with your models loaded – Dish.count works there as here. With has_many and belongs_to models link up (an order has many dishes), and the same code talks to PostgreSQL or MySQL once config/database.yml says so.Guest the validation that a name is required, and make regulars the guests with at least 2 visits (where with a ? placeholder). The cell should end with ["Kaz"].ActiveRecord::Schema.define do
create_table :guests, force: true do |t|
t.string :name
t.integer :visits
t.timestamps
end
end
class Guest < ActiveRecord::Base
# validates ...
end
Guest.create!(name: "Kaz", visits: 3)
Guest.create!(name: "Ada", visits: 1)
regulars = Guest.all # only the guests with at least 2 visits, please
regulars.map(&:name)