Tables that belong together
A menu has categories, and every dish is in one of them. In a database that is a column: category_id on the dishes table holds the id of the category's row – a foreign key. Active Record turns that column into two methods, declared with one line on each side: has_many :dishes in Category, belongs_to :category in Dish. Everything else – the joins, the ids, the caching – it does from the names. Lesson 57 had the one table; here come two:
install_gem "rails"
require "active_record"
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "menu.db")
ActiveRecord::Base.belongs_to_required_by_default = true # as rails new sets it
ActiveRecord::Schema.define do
create_table :categories, force: true do |t|
t.string :name
end
create_table :dishes, force: true do |t|
t.string :name
t.decimal :price, precision: 6, scale: 2
t.references :category # the column category_id, with an index
t.timestamps
end
end
class Category < ActiveRecord::Base
has_many :dishes
end
class Dish < ActiveRecord::Base
belongs_to :category
end
starters = Category.create!(name: "Starters")
mains = Category.create!(name: "Mains")
starters.dishes.create!(name: "Soup", price: 3)
mains.dishes.create!(name: "Bacon", price: 4.5)
mains.dishes.create!(name: "Egg", price: 2)
Dish.countt.references :category is the migration's word for "a category_id column, with an index", and starters.dishes.create! fills it in: a dish made through the category's dishes knows its category. The two INSERTs in the log show it. From here on both directions are a method call, and a relation like mains.dishes can be queried on like any other:
egg = Dish.find_by(name: "Egg")
puts egg.category.name
mains = Category.find_by(name: "Mains")
puts mains.dishes.map(&:name).inspect
puts mains.dishes.sum(:price)
puts Dish.joins(:category).where(categories: { name: "Mains" }).pluck(:name).inspect
Category.includes(:dishes).each do |category|
puts "#{category.name}: #{category.dishes.map(&:name).join(", ")}"
end
orphan = Dish.new(name: "Orphan", price: 1)
orphan.valid?
orphan.errors.full_messagesegg.category loads the category, mains.dishes the dishes – each one query, WHERE category_id = ?, in the log. joins(:category) asks the database to connect the two tables, so you can filter dishes by their category's name in one query; includes(:dishes) loads all categories and all their dishes in two queries instead of one per category – the famous N+1 problem, solved in a word. And the orphan: belongs_to is also a validation, Category must exist, when belongs_to_required_by_default is on, as it is in every app rails new makes.
bin/rails generate model Dish name:string price:decimal category:references writes the migration with t.references and the belongs_to into the model for you; the has_many on the other side is yours to add. Beyond this: has_many :through for many-to-many (an order has many dishes through its order items), dependent: :destroy so a category takes its dishes with it, and has_one.has_many :specials in Cook, belongs_to :cook in Special – so that the cell creates Kaz's two specials and ends with their names.ActiveRecord::Schema.define do
create_table :cooks, force: true do |t|
t.string :name
end
create_table :specials, force: true do |t|
t.string :name
t.references :cook
end
end
class Cook < ActiveRecord::Base
# has_many ...
end
class Special < ActiveRecord::Base
# belongs_to ...
end
kaz = Cook.create!(name: "Kaz")
Special.create!(name: "Rösti", cook: kaz)
Special.create!(name: "Fondue", cook: kaz)
kaz.specials.map(&:name)