多対多
料理にはたくさんの材料があり、ベーコンはたくさんの料理に入っています。これは外部キー1つでは表せません。料理のテーブルのingredient_idという列が持てるidは1つだけで、材料のテーブルのdish_idでも同じです。そこで、3つ目のテーブルが組み合わせを持ちます。中間テーブル(join table)のdish_ingredientsです。「この料理にはこの材料が入っている」ごとに1行で、どちらか一方ではなく組み合わせに属するもの、たとえば朝食にベーコンをどれだけ使うかを入れる場所もあります。このテーブルには自分のモデルDishIngredientがあり、両側へのbelongs_toを持ちます。レッスン61の関連付けです。新しいのは、それを通り抜ける1行、has_many :ingredients, through: :dish_ingredientsです。
レッスンの最後でメニューをまたページにするので、まずはレッスン60のアプリを用意します。
install_gem "rails"
require "rails"
require "action_controller/railtie"
require "active_record"
# Railsのレッスンと同じアプリです。起動はページごとに一度なので同じクラスを使い、
# フォルダは、まだないときだけ作ります
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.version今度はテーブルが4つです。中間テーブルの参照に付けたforeign_key: trueによって、どのdish_idも存在する料理を指しているかを、データベース自身が確かめます。これはレッスンの最後まで覚えておいてください。drop_tableが最初にあるのも、そのためです。ほかのテーブルの行がまだ指しているあいだは、データベースはそのテーブルを消させてくれません。
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "db/menu.sqlite3")
ActiveRecord::Base.belongs_to_required_by_default = true # rails new の設定と同じです
ActiveRecord::Schema.define do
drop_table :dish_ingredients, if_exists: true # 最初に消します。ほかの2つを指しているからです
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| # 中間テーブル:料理と材料の組み合わせごとに1行
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 # dependent: については、もっと下で
has_many :ingredients, through: :dish_ingredients
end
class DishIngredient < ActiveRecord::Base # 中間モデル
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 # 中間テーブルの行を書き込みます
toast = mains.dishes.create!(name: "Egg on toast", price: 4)
toast.ingredients << egg << bread
breakfast.ingredients.pluck(:name)breakfast.dish_ingredients.create!は、分量付きで中間テーブルの行を書き込みます。rosti.ingredients << potatoも分量なしで1行書き込みます。間にどのテーブルがあるかを、Active Recordは知っているのです。そしてbreakfast.ingredientsはクエリ1回です。ログにはINNER JOIN "dish_ingredients"が出ています。逆方向も同じように動きます。レッスン61で外部キー1つに対してやったこと、つまりjoins、where、includesは、中間テーブルを通しても使えます。
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)] }ベーコンは2つの料理に入っていて、卵も同じです。joins(:ingredients)は3つのテーブルを全部つないでくれます。includes(:ingredients)は、料理がいくつあっても、料理、中間テーブルの行、材料の3回のクエリで全部を読み込みます。分量が欲しいときは、自分でdish_ingredientsを通ります。分量は材料ではなく、組み合わせに属するからです。
どのページにも同じ枠
いよいよメニューをページにします。サイトのどのページにも同じ枠、つまりヘッダー、フッター、スタイルシートがあり、変わるのは真ん中だけです。Railsではこの枠をレイアウトと呼びます。app/views/layouts/application.html.erbは1枚まるごとのHTMLページで、アクションのビューが入る場所に<%= yield %>があります。ビューはレイアウトのほかの場所を埋めることもできます。content_for :title, @dish.nameが部品をしまい、レイアウトのyield :titleがそれを差し込み、content_for?(:title)は部品があるかどうかを尋ねます。
どのレイアウトが使われるのでしょうか。Railsはまずコントローラーの名前のレイアウト(layouts/menu)を探し、次にスーパークラスの名前のものを探します。ApplicationControllerなのでlayouts/applicationです。どのRailsアプリにも、すべてのコントローラーが継承するApplicationControllerがあるのは、このためです。(これまでのレッスンのコントローラーはActionController::Baseを直接継承していたので、レイアウトはありませんでした。)
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
# アプリのすべてのコントローラーがこれを継承します
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, "/"ログにもRendering menu/index.html.erb within layouts/applicationと出ています。料理を開いてみてください。ヘッダーに› Bacon and eggsが付きます。showビューのcontent_forです。同じ名前は<title>にも入り、本物のブラウザならタブに表示されます(ミニブラウザにはタブがありません)。ヘッダーとフッターは一度書くだけで、アプリのこれからのすべてのページに使われます。
親がいなくなるとき
料理を削除すると、中間テーブルの行はどうなるのでしょうか。それを決めるのがdependent:オプションで、上のDishにはhas_many :dish_ingredients, dependent: :destroyがあります。Ingredientのhas_many :dish_ingredientsには、このオプションがありません。
# dependent: :destroy なので、中間テーブルの行が先に消えます
Dish.find_by(name: "Egg on toast")&.destroy
puts DishIngredient.count
puts Ingredient.pluck(:name).inspect # 材料は残ります
bacon = Ingredient.find_by(name: "Bacon")
begin
bacon.destroy # ここには dependent: がなく、ベーコンはまだ2つの料理で使われています
rescue ActiveRecord::InvalidForeignKey => error
puts error.message
end
Ingredient.countトーストは中間テーブルの2行を道連れにしました。ログを見ると、Active Recordはそれらを読み込んで1行ずつ削除し、それから料理を削除しています。全部が1つのトランザクションの中です。卵とパンは残ります。もともと料理のものではないからです。上のミニブラウザでChunky's Dinerをクリックしてみてください。トーストはメニューから消えています。ベーコンは消せませんでした。中間テーブルの2行がまだベーコンを指していて、foreign_key: trueのおかげでデータベースが確かめ、断ったのです。ActiveRecord::InvalidForeignKeyで、トランザクションはロールバックされました。外部キーがなければ、削除は黙って通り、どこも指さない行が残っていたでしょう。dependent:に指定できるのは次のとおりです。
:destroy:子をひとつずつ読み込んでdestroyします。子自身のdependent:とコールバックも動きます:delete_all:全部をDELETE1回で消します。速いですが、コールバックもその先の削除もありません:nullify:子は残し、外部キーをNULLにします。単独で存在できる子のためです(belongs_to … optional: true):restrict_with_error:削除を断ります。destroyはエラーメッセージ付きでfalseを返します。ベーコンのように、まだ使われているもののためです
bin/rails generate model DishIngredient dish:references ingredient:references amount:stringが、2つのbelongs_to付きの中間モデルと、foreign_key: true付きのマイグレーションを書いてくれます。両側のhas_manyは自分で足します。application.html.erbとApplicationControllerはrails newが書いてくれますし、コントローラーにlayout "admin"と書けば別のレイアウトを選べます。モデルも自分の列もない中間テーブルならhas_and_belongs_to_manyですが、たいていのアプリはhas_many :throughを選びます。分量のような列は、必ず出てくるからです。deliveriesを中間テーブルにした多対多です。Supplierに2つの関連付けを付けましょう。仕入れ先がなくなるときに配達も一緒に消えるように(dependent: :destroy)has_many :deliveriesを、そしてそれを通してhas_many :productsを宣言します。今のままでは、dairy.destroyが上と同じ外部キーのエラーで失敗します。うまくいけば、このセルは農場の食材、残った配達の数、残った牛乳の配達の数で終わります。[["Eggs", "Milk"], 2, 1]です。ActiveRecord::Schema.define do
drop_table :deliveries, if_exists: true # 最初に消します。ほかの2つを指しているからです
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 ...(仕入れ先がなくなるとき、その配達も一緒に消えるように)
# 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 # 乳製品店が閉店します
[farm.products.order(:name).pluck(:name), Delivery.count, milk.deliveries.count]