1:N 一對多

如果我們希望每間商店可以販售許多種飲料,可以使用一對多模式來進行關連。

先建立 Drink 這個 Model:
rails g model Drink name price:decimal store_id:integer

目前的資料關聯設計像下圖

先把 model 之間的關聯建立好

drink.rb

1
2
3
class Drink < ApplicationRecord
belongs_to :stores
end

store.rb

1
2
3
4
class Store < ApplicationRecord
has_many :drinks
belongs_to :owner
end

方法建立

跟 has_one 一樣,設定 has_many :drinks 後會多了以下幾個方法,belongs_to 建立的方法跟 1:1 是一樣,這邊就不多提:

drinks
drinks=
build
create

console 測試看看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 找回上次建立的飲料店
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 的飲料

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>]

也可以反查出某款飲料是哪間店

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 找回最後建立的飲料(珍珠奶茶)
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>

參考資料:

  1. 為你自己學 Ruby on Rails