續上一篇,今天要來講的是一對多
還記得嗎?我們昨天說的
我們希望每一間商店可以販售許多種商品,這就是我們所謂的一對多!
2.執行 rails db:migrate
has_many
將設定成為(一對多)4.反之,在Product Model 加上belongs_to
以上,這些動作,他大概的關聯圖如下表:
老樣子,我們進 rails c
看看
> store1 = Store.first
(0.5ms) SELECT sqlite_version(*)
Store Load (0.1ms) SELECT "stores".* FROM "stores" ORDER BY "stores"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Store id: 1, title: "良心商店", tel: nil, address: nil, user_id: 1, created_at: "2021-10-10 09:...
2.建立兩件商品的資料,分別是product1和product2
> product1 = Product.new(name:"吃吃喝喝商店",price: 200)
=> #<Product id: nil, name: "吃吃喝喝商店", description: nil, price: 0.2e3, is_available: nil, store...
> product2 = Product.new(name:"我想要飛",price: 1000)
=> #<Product id: nil, name: "我想要飛", description: nil, price: 0.1e4, is_available: nil, store_id:...
3.把這兩個商品用陣列的方式,丟進去給store1
> store1.products = [product1, product2]
Product Load (0.4ms) SELECT "products".* FROM "products" WHERE "products"."store_id" = ? [["store_id", 1]]
TRANSACTION (0.1ms) begin transaction
Product Create (0.4ms) INSERT INTO "products" ("name", "price", "store_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["name", "吃吃喝喝商店"], ["price", 200.0], ["store_id", 1], ["created_at", "2021-10-11 08:29:21.580320"], ["updated_at", "2021-10-11 08:29:21.580320"]]
Product Create (0.1ms) INSERT INTO "products" ("name", "price", "store_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["name", "我想要飛"], ["price", 1000.0], ["store_id", 1], ["created_at", "2021-10-11 08:29:21.581872"], ["updated_at", "2021-10-11 08:29:21.581872"]]
TRANSACTION (0.5ms) commit transaction
=> [#<Product id: 1, name: "吃吃喝喝商店", description: nil, price: 0.2e3, is_available: nil, store_...
4.接下來,讓我們來看看,資料是不是真的有寫進去
> store1.products
=> #<ActiveRecord::Associations::CollectionProxy [
#<Product id: 1, name: "吃吃喝喝商店", description: nil, price: 0.2e3, is_available: nil, store_id: 1, created_at: "2021-10-11 08:29:21.580320000 +0000", updated_at: "2021-10-11 08:29:21.580320000 +0000">,
#<Product id: 2, name: "我想要飛", description: nil, price: 0.1e4, is_available: nil, store_id: 1, created_at: "2021-10-11 08:29:21.581872000 +0000", updated_at: "2021-10-11 08:29:21.581872000 +0000">
]>
5.確認這些資料有幾筆?
> store1.products.count
(0.5ms) SELECT COUNT(*) FROM "products" WHERE "products"."store_id" = ? [["store_id", 1]]
=> 2
今天就先到這邊,明天我們來講多對多!
最近剛好有在練習這區塊,就把一些書上的重點來寫一篇。
看看自己在步驟上面是否有記住
希望飛得慢,可以成功抵達終點拉~
參考資料:為自己學Ruby on Rails