Single-table inheritance And Polymorphic
STI 與 多型關聯 的 combo 技
先來假設一個情境
使用者可以訂閱不同的方案,年繳或月繳之類的
1. 單一表格繼承 STI (Single-table inheritance)
YearPlan和MonthPlan共用,Plan這個table
1 | # Table name: plans |
STI 單一表格繼承,會根據你使用建立的 model 在 plans 的這個 table 的 type 中紀錄 model_name
1 | # model/plan.rb |
ex.
1 | # rails console |
這樣的情況,會在 plans 的 table 中 建立一筆 type 分別為 "YearPlan"、"MonthPlan" 的 record
而在 console YearPlan.last,只是去 Plans 這個 table 找
因為這個功能,在 rails 裡,column 的名字不能亂取成 type
2. 多型關聯 polymorphic
先假設另外一個單純的情境來講 polymorphic,以 Rails實戰聖經裡面的例子,airtcle、photo 都可以被 comment
所以 comment 可以用多型的關係指向不同的 model 關聯。
1 | class Comment < ApplicationRecord |
1 | article = Article.first |
到這裡我一直都認為,在寫入的 commentable_type ,是去抓取物件的 model(class) name,直到他與 STI 相遇了……
回到 STI 與 polymorphic
使用者可以分別訂閱不同的方案,但其實可以開成一個 model 就好。
1 | class Subscription < ApplicationRecord |
這樣的情況預期可以讓 Subscription 根據 planable 帶進來的 record 去找到相關連的 object
1 | my_plan = YearPlan.last |

接著讓我們來看看 這個 record

planable_type 寫的是 寫的是 Plan ,不是 YearPlan ,所以看起來是去抓他的 table_name,要注意!
💡 解法
1 | before_validation :set_type |
若有任何指教,歡迎留言給我。🙏