Many to many
A dish has many ingredients, and bacon is in many dishes. One foreign key cannot say that: a column ingredient_id on the dishes table holds one id, and so would dish_id on the ingredients table. So a third table holds the pairs – a join table, dish_ingredients, one row for each "this dish has this ingredient", with room for what belongs to the pair and to neither side alone: how much bacon goes into the breakfast. It gets a model of its own, DishIngredient, with a belongs_to to each side – the associations of lesson 61. What is new is the line that walks through it: has_many :ingredients, through: :dish_ingredients.
At the end of the lesson the menu becomes a page again, so first the app from lesson 60:
install_gem "rails"
require "rails"
require "action_controller/railtie"
require "active_record"
# the app of the Rails lesson: it boots once per page, so this is the same
# class, and its folders are made again only if they are missing
FileUtils.mkdir_p("/tmp/diner/app/views")
FileUtils.mkdir_p("/tmp/diner/config")
routes = "/tmp/diner/config/routes.rb"
File.write(routes, "Rails.application.routes.draw do\nend\n") unless File.exist?(routes)
class DinerApp < Rails::Application
config.root = "/tmp/diner"
config.eager_load = false
config.consider_all_requests_local = true
config.logger = Logger.new(STDOUT)
end
DinerApp.initialize! unless DinerApp.initialized?
Rails.versionFour tables now. foreign_key: true on the join table's references makes the database itself check that every dish_id names a dish that exists – remember that for the end of the lesson. It is also why drop_table comes first: the database does not let a table go while rows of another still point into it.
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "db/menu.sqlite3")
ActiveRecord::Base.belongs_to_required_by_default = true # as rails new sets it
ActiveRecord::Schema.define do
drop_table :dish_ingredients, if_exists: true # first: it points at the other two
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
end
create_table :ingredients, force: true do |t|
t.string :name
end
create_table :dish_ingredients do |t| # the join table: one row per dish and ingredient
t.references :dish, foreign_key: true
t.references :ingredient, foreign_key: true
t.string :amount
end
end
class Category < ActiveRecord::Base
has_many :dishes
end
class Dish < ActiveRecord::Base
belongs_to :category
has_many :dish_ingredients, dependent: :destroy # more on dependent: further down
has_many :ingredients, through: :dish_ingredients
end
class DishIngredient < ActiveRecord::Base # the join model
belongs_to :dish
belongs_to :ingredient
end
class Ingredient < ActiveRecord::Base
has_many :dish_ingredients
has_many :dishes, through: :dish_ingredients
end
mains = Category.create!(name: "Mains")
bacon, egg, potato, bread = %w[Bacon Egg Potato Bread].map { |name| Ingredient.create!(name: name) }
breakfast = mains.dishes.create!(name: "Bacon and eggs", price: 6.5)
breakfast.dish_ingredients.create!(ingredient: bacon, amount: "3 rashers")
breakfast.dish_ingredients.create!(ingredient: egg, amount: "2")
rosti = mains.dishes.create!(name: "Rösti", price: 5)
rosti.ingredients << potato << bacon # writes the rows of the join table
toast = mains.dishes.create!(name: "Egg on toast", price: 4)
toast.ingredients << egg << bread
breakfast.ingredients.pluck(:name)breakfast.dish_ingredients.create! writes a row of the join table with its amount; rosti.ingredients << potato writes one too, without an amount – Active Record knows which table stands in between. And breakfast.ingredients is a single query: the log shows INNER JOIN "dish_ingredients". The other direction works the same way, and what lesson 61 did with one foreign key – joins, where, includes – works through the join table:
bacon = Ingredient.find_by(name: "Bacon")
puts bacon.dishes.pluck(:name).inspect
puts Dish.joins(:ingredients).where(ingredients: { name: "Egg" }).pluck(:name).inspect
breakfast = Dish.find_by(name: "Bacon and eggs")
breakfast.dish_ingredients.includes(:ingredient).each do |line|
puts "#{line.amount} #{line.ingredient.name}"
end
Dish.includes(:ingredients).map { |dish| [dish.name, dish.ingredients.map(&:name)] }Bacon is in two dishes, and so is the egg. joins(:ingredients) joins all three tables for you; includes(:ingredients) loads everything in three queries – the dishes, their rows in the join table, the ingredients – however many dishes there are. For the amount you go through dish_ingredients yourself: it belongs to the pair, not to the ingredient.
One frame for every page
Now the menu goes on a page. Every page of a site has the same frame – a header, a footer, the stylesheet – and only the middle changes. In Rails that frame is a layout: app/views/layouts/application.html.erb, a whole HTML page with <%= yield %> where the action's view goes. A view can fill other places in the layout as well: content_for :title, @dish.name stores a piece, yield :title in the layout puts it there, and content_for?(:title) asks whether there is one.
Which layout? Rails looks for one named after the controller (layouts/menu), then for one named after its superclass – ApplicationController, so layouts/application. That is why every Rails app has an ApplicationController that all its controllers inherit from. (The controllers of the earlier lessons inherited straight from ActionController::Base and got no layout.)
Rails.root.join("config/routes.rb").write(<<~ROUTES)
Rails.application.routes.draw do
root "menu#index"
get "menu/:id", to: "menu#show", as: :menu_dish
end
ROUTES
DinerApp.reload_routes!
views = Rails.root.join("app/views")
views.join("layouts").mkpath
views.join("layouts/application.html.erb").write(<<~ERB)
<!DOCTYPE html>
<html>
<head>
<title><%= content_for?(:title) ? yield(:title) : "Menu" %> · Chunky's Diner</title>
<style>
header { background: #c14a2e; color: white; padding: 6px 10px; }
header a { color: white; }
footer { margin-top: 16px; color: gray; font-size: small; }
</style>
</head>
<body>
<header>
<%= link_to "Chunky's Diner", root_path %>
<% if content_for?(:title) %> › <%= yield :title %><% end %>
</header>
<%= yield %>
<footer>Open daily from 7 · chunky bacon guaranteed</footer>
</body>
</html>
ERB
views.join("menu").mkpath
views.join("menu/index.html.erb").write(<<~ERB)
<h2>Menu</h2>
<ul>
<% @dishes.each do |dish| %>
<li>
<%= link_to dish.name, menu_dish_path(dish) %>
(<%= dish.ingredients.map(&:name).join(", ") %>)
</li>
<% end %>
</ul>
ERB
views.join("menu/show.html.erb").write(<<~ERB)
<% content_for :title, @dish.name %>
<h2><%= @dish.name %></h2>
<ul>
<% @dish.dish_ingredients.each do |line| %>
<li><%= line.amount %> <%= line.ingredient.name %></li>
<% end %>
</ul>
ERB
# every controller of the app inherits from it
class ApplicationController < ActionController::Base
end
class MenuController < ApplicationController
def index
@dishes = Dish.includes(:ingredients).order(:name)
end
def show
@dish = Dish.find(params[:id])
end
end
show_browser DinerApp, "/"The log says it: Rendering menu/index.html.erb within layouts/application. Open a dish: the header grows a › Bacon and eggs – the show view's content_for – and the same name goes into the <title>, which a real browser shows on its tab (the mini browser has no tab). The header and the footer are written once, for every page the app will ever have.
When the parent goes
What becomes of the rows in the join table when a dish is deleted? That is what the dependent: option decides, and Dish above has has_many :dish_ingredients, dependent: :destroy. The has_many :dish_ingredients of Ingredient has no such option:
# dependent: :destroy - its rows in the join table go first
Dish.find_by(name: "Egg on toast")&.destroy
puts DishIngredient.count
puts Ingredient.pluck(:name).inspect # the ingredients stay
bacon = Ingredient.find_by(name: "Bacon")
begin
bacon.destroy # no dependent: here, and two dishes still use bacon
rescue ActiveRecord::InvalidForeignKey => error
puts error.message
end
Ingredient.countThe toast took its two rows of the join table along: in the log Active Record loads them, deletes them one by one, then the dish – all in one transaction. The egg and the bread stay; they were never the dish's to delete. Click Chunky's Diner in the mini browser above: the toast is off the menu. The bacon could not go: two rows of the join table still point at it, foreign_key: true made the database check, and it refused – ActiveRecord::InvalidForeignKey, the transaction rolled back. Without the foreign key the delete would have gone through quietly and left rows that point at nothing. What dependent: can say:
:destroy– load every child anddestroyit, with its owndependent:and callbacks:delete_all– oneDELETEfor all of them: quicker, but no callbacks and nothing further down:nullify– keep the children and set their foreign key toNULL, for children that can stand alone (belongs_to … optional: true):restrict_with_error– refuse:destroyreturnsfalsewith an error message, for things like the bacon that are still in use
bin/rails generate model DishIngredient dish:references ingredient:references amount:string writes the join model with both belongs_to and a migration with foreign_key: true; the has_many lines on the two sides are yours to add. rails new writes application.html.erb and ApplicationController for you, and layout "admin" in a controller picks another layout. A join table without a model and without columns of its own is has_and_belongs_to_many – most apps take has_many :through, because a column like the amount always turns up.deliveries as the join table. Give Supplier its two associations: has_many :deliveries, so that a supplier takes its deliveries along when it goes (dependent: :destroy), and has_many :products through them. As it stands, dairy.destroy fails with the foreign key error from above; once it works, the cell ends with the farm's products, the deliveries left and the deliveries of milk left: [["Eggs", "Milk"], 2, 1].ActiveRecord::Schema.define do
drop_table :deliveries, if_exists: true # first: it points at the other two
create_table :suppliers, force: true do |t|
t.string :name
end
create_table :products, force: true do |t|
t.string :name
end
create_table :deliveries do |t|
t.references :supplier, foreign_key: true
t.references :product, foreign_key: true
end
end
class Supplier < ActiveRecord::Base
# has_many ... (its deliveries go when the supplier goes)
# has_many ... through ...
end
class Delivery < ActiveRecord::Base
belongs_to :supplier
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :deliveries
end
farm = Supplier.create!(name: "Moser Farm")
dairy = Supplier.create!(name: "Valley Dairy")
eggs, milk, cream = %w[Eggs Milk Cream].map { |name| Product.create!(name: name) }
Delivery.create!(supplier: farm, product: eggs)
Delivery.create!(supplier: farm, product: milk)
Delivery.create!(supplier: dairy, product: milk)
Delivery.create!(supplier: dairy, product: cream)
dairy.destroy # the dairy closes
[farm.products.order(:name).pluck(:name), Delivery.count, milk.deliveries.count]