つながり合うテーブル
メニューにはカテゴリーがあり、どの料理もそのどれかに入っています。データベースでは、それは1つの列です。料理のテーブルのcategory_idが、カテゴリーの行のidを持ちます。外部キーです。Active Recordはこの列を2つのメソッドに変えます。宣言は両側に1行ずつ、Categoryにhas_many :dishes、Dishにbelongs_to :categoryです。そのほかのこと、つまり結合もidもキャッシュも、名前から全部やってくれます。レッスン57ではテーブルは1つでした。ここでは2つになります。
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 # rails new の設定と同じです
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 # category_id という列と、そのインデックス
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は、マイグレーションの言葉で「category_idという列と、そのインデックス」です。そしてstarters.dishes.create!がそこを埋めます。カテゴリーのdishesを通して作った料理は、自分のカテゴリーを知っています。ログの2つのINSERTがそれを示しています。ここからは、どちらの向きもメソッドの呼び出し1つで、mains.dishesのようなリレーションには、ほかのものと同じように問い合わせができます。
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はカテゴリーを、mains.dishesは料理を読み込みます。それぞれログにはWHERE category_id = ?のクエリが出ます。joins(:category)は、2つのテーブルをつなぐようデータベースに頼むので、料理をカテゴリーの名前で1回のクエリで絞り込めます。includes(:dishes)は、すべてのカテゴリーとそのすべての料理を、カテゴリーごとに1回ではなく、2回のクエリで読み込みます。有名なN+1問題が、ひと言で片づきます。そして孤児の料理です。belongs_to_required_by_defaultがオンのとき、rails newが作るどのアプリでもそうなのですが、belongs_toはバリデーションでもあります。Category must existです。
bin/rails generate model Dish name:string price:decimal category:referencesが、t.references付きのマイグレーションと、モデルの中のbelongs_toを書いてくれます。反対側のhas_manyは自分で足します。この先には、多対多のためのhas_many :through(注文は注文明細を通して多くの料理を持ちます)、カテゴリーが料理を道連れにするdependent: :destroy、それにhas_oneがあります。Cookにhas_many :specials、Specialにbelongs_to :cookです。そうすれば、このセルはKazの2つの得意料理を作って、その名前で終わります。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)