iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

非本科之30天Ruby / Rails學習筆記系列 第 14

Day14: 淺談Model資料表關聯

不管用哪個程式語言或框架寫網站,多數會有資料庫的應用,資料與資料之間一定會有關聯性,那要如何在不同Model設立資料關係,這裏會用很簡單的例子去試著理解什麼是資料表關聯。

Active Record

根據手冊:「Active Record 是 MVC 的 M(Model),表現商業邏輯與資料的層級,負責新增與操作需要持久存在資料庫裡的資料」

看起來有點抽象,在我的理解大概就是這個概念:

Active Record = 把資料做成物件(是一種ORM框架)
物件 = 欄位 + 基本操作 + 商業邏輯

這樣寫似乎還是有點抽象,但其實可以想像成:

Model = ActiveRecord.new

用店面舉例

先預設我們有3個Model:

  • Owner
  • Stroe
  • Product

o1 = Owner.create(name: 'Louis')

s1 = Store.new(title: 'Louis Shop')
此時s1的owner_id還是空的

o1.store = s1
把 Store 指定給 Owner
s1的Owner_id就有3了

可用 create (本身包含.save)

o1 = Owner.create(name: 'Sherly')
o1.create_store(title: 'Ruby Shop')

用build(本身不包含save)

還未.save前,可看到shop的id是空的

.save後


用new不會存進資料庫,必須額外.save

用另一個角度

只要有任一方有存入資料庫,就可以設定關聯性,不須雙方都存入資料庫

.create_store => 直接寫入資料庫
.build_store =>  建立,但未寫入資料庫

has_one

(類似 Cat = Animail.new的概念)
•store
•store=
•build_store
•create_store

belongs_to

belongs_to 也是一個類別方法
執行belongs_to :owner,只有產生以下兩個方法:
•owner
•owner=

has_many

products
products=
build
create
#個別建立物件
s1 = Store.first
p1 = Product.new(name: 'iphone')
p2 = Product.new(name: 'ipad')

#方法一:可以一次塞入多個到s1
s1.products = [p1, p2]

#方法二:只能塞一個到s1
s1.products.create(name: 'Mac')

has_many: through 多對多

跟has_many用起來差不多
需要第三方資料表來儲存兩邊資訊
第三方資料表通常只存放兩邊id,並且belong_to兩邊的Model

rails g WareHouse sotre:references product:references

或

rails g WareHouse sotre_id:integer product_id:integer

#store.rb
class Store < ApplicationRecord
  has_many :ware_houses
  has_many :products, through: :ware_houses #透過第三方
end

#product.rb
class Product < ApplicationRecord
  # belongs_to :store
  has_many :ware_houses
  has_many :stores, through: :ware_houses #透過第三方
end
s1 = Store.first
s2 = Store.second
p1 = Product.first
p2 = Product.second
p3 = Product.third

試著建立這樣的關係:


下圖:
p2.stores ->p2商品再哪間店有貨
s1.owner  ->s1店面的店長是誰
s2.products -> s2店面有哪些商品

參考資料:
Model 基本操作

“I realized early on that success was tied to not giving up. Most people in this business gave up and went on to other things. If you simply didn’t give up, you would outlast the people who came in on the bus with you.”

— Harrison Ford, Actor

本文同步發佈於: https://louiswuyj.tw/


上一篇
Day13: Ruby on Rails 的 .nil? .empty? .blank? .present?
下一篇
Day15: Rails中的Gemfile
系列文
非本科之30天Ruby / Rails學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言