如果我們希望每間商店可以販售許多種飲料,可以使用一對多模式來進行關連。
先建立 Drink 這個 Model:rails g model Drink name price:decimal store_id:integer
目前的資料關聯設計像下圖
先把 model 之間的關聯建立好
drink.rb
class Drink < ApplicationRecord
belongs_to :stores
end
store.rb
class Store < ApplicationRecord
has_many :drinks
belongs_to :owner
end
跟 has_one 一樣,設定 has_many :drinks 後會多了以下幾個方法,belongs_to 建立的方法跟1:1是一樣,這邊就不多提:
drinks
drinks=
build
create
# 找回上次建立的飲料店
s1 = Store.last
id: 1,
name: "五石蘭",
tel: "031234567",
address: "新竹縣",
owner_id: 1,
created_at: Fri, 07 Oct 2022 07:22:23.353390000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:22:23.353390000 UTC +00:00>
# 直接用 Drink 建立好再丟給 store
d1 = Drink.new(name:"紅茶", price:30)
id: 1,
name: "紅茶",
price: 0.6e2,
store_id: 1,
created_at: Fri, 07 Oct 2022 07:52:50.417919000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:52:50.417919000 UTC +00:00>,
#1 把 d1 放到陣列中指定給 s1.drinks
s1.drinks = [d1]
#2 把 d1 插入到 s1.drinks 陣列
s1.drinks << d1
# 透過 store 去建立 drink
s1.drinks.create(name:"珍珠奶茶", price:60)
id: 2,
name: "珍珠奶茶",
price: 0.6e2,
store_id: 1,
created_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00>]
查出所有s1的飲料
s1.drinks
id: 1,
name: "紅茶",
price: 0.3e2,
store_id: 1,
created_at: Fri, 07 Oct 2022 07:52:50.417919000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:52:50.417919000 UTC +00:00>,
id: 2,
name: "珍珠奶茶",
price: 0.6e2,
store_id: 1,
created_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00>]
也可以反查出某款飲料是哪間店
# 找回最後建立的飲料(珍珠奶茶)
d2 = Drink.last
id: 2,
name: "珍珠奶茶",
price: 0.6e2,
store_id: 1,
created_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:54:55.118310000 UTC +00:00>]
# 因為 belongs_to 可以利用 store 方法反查
d2.store
id: 1,
name: "五石蘭",
tel: "031234567",
address: "新竹縣",
owner_id: 1,
created_at: Fri, 07 Oct 2022 07:22:23.353390000 UTC +00:00,
updated_at: Fri, 07 Oct 2022 07:22:23.353390000 UTC +00:00>
參考資料: