上一章已經幫兩位 owner
成功開店了;接下來,我們幫他們進駐一些商品 (product),一間店不可能只有一件商品,所以我們這邊要用到一對多關聯。
先來畫一張關係圖,等一下我們建關聯時會比較輕鬆:
這張圖,翻成白話文就是一個 owner 有一間 store,一間 store 有很多 product;同時,product 屬於 store,store 屬於 owner。
我們先建一個 Product
Model:
$ rails g model Project name price:integer store:references
再來建立 Model 間的關聯
# store.rb
class Store < ApplicationRecord
has_may :products
belongs_to :owner
end
# project.rb
class Product < ApplicationRecord
belongs_to :store
end
當關聯建立好之後,has_many
就跟 has_one
一樣,會有以下方法:
我們先幫 store1
添加一些商品吧!
首先我們要先找到 store1
:
>> store1 = Store.first
=> #<Store id: 1, title: "超夯麵包店", address: "台北", owner_id: 1, created_at: "2022-10-12 04:17:30.170669000 +0000", updated_at: "2022-10-12 04:17:30.170669000 +0000">
再來我們增加兩件商品:
>> product1 = Product.new(name: "菠蘿麵包", price: 50)
>> product2 = Product.new(name: "檸檬塔", price: 70)
建立完之後,將 product1
和 product2
這兩件商品給 store1
>> store1.products = [product1, product2]
=> #<ActiveRecord::Associations::CollectionProxy [#<Product id: 1, name: "菠蘿麵包", price: 50, store_id: 1, created_at: "2022-10-12 09:47:07.978598000 +0000", updated_at: "2022-10-12 09:47:07.978598000 +0000">, #<Product id: 2, name: "檸檬塔", price: 70, store_id: 1, created_at: "2022-10-12 09:47:07.981780000 +0000", updated_at: "2022-10-12 09:47:07.981780000 +0000">]>
除了用上面的方式把 project
加到 store1
中,還可以用這個方式:
>> product3 = Product.new(name: "提拉米蘇", price: 150)
>> store1.Product << product3
TRANSACTION (0.4ms) begin transaction
Product Create (0.3ms) INSERT INTO "products" ("name", "price", "store_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["name", "提拉米蘇"], ["price", 150], ["store_id", 1], ["created_at", "2022-10-12 09:49:43.441025"], ["updated_at", "2022-10-12 09:49:43.441025"]]
確認資料是否有進到 store1
>> store1.products
確認資料數量:
>> store1.products.count
SELECT COUNT(*) FROM "products" WHERE "products"."store_id" = ? [["store_id", 1]]
=> 3
我們也可以用 project
的角度去查他有在哪一間店有賣:
>> product2.store
=> #<Store id: 1, title: "超夯麵包店", address: "台北", owner_id: 1, created_at: "2022-10-12 09:39:21.126447000 +0000", updated_at: "2022-10-12 09:39:21.126447000 +0000">
參考資料: