如何複寫Model table 慣例 / 資料存取刪除簡介

Posted by Anthony Chao on 2019-09-07

覆寫 model 中 table name 跟 primary key 慣例

來到第四段這邊提到覆蓋掉原本設定的做法
也就是 model 大寫單數 table 小寫複數的慣例如果要推翻掉要怎麼做呢?
在 ActiveRecord::Base 中有個 table_name= 的方法,要先用它覆蓋原本的設定

1
self.table_name = "my_products"

接著還沒結束,要去這個 table 相對應的 yml 檔中使用 set_fixture_class 方法設定這個 table 的相對應 model,有沒有感覺到不遵循 Coc 要遭到怎樣的報應了 XD?

1
2
3
4
5
6
#my_products.yml
class ProductTest < ActiveSupport::TestCase
set_fixture_class my_products: Product
fixtures :my_products
...
end

上一篇有講到 primary_key rails 會 default 幫你設定一個 ID 欄位,如果要改掉的話就用 primary_key= 這個方法

1
self.primary_key = "product_id"

資料存取與刪除

下面有講到一些比較基礎的 CRUD 方法,雖然他很快的帶過了,因為後面還會補充,但我還是在這裡先寫下最基本的方法

存資料:
存資料的方法主要有三種: create / update / save
save 是最基本的,把這筆資料存到資料庫中,那麼 save 跟 create 又差在哪裡呢?可以看下面的例子說明

1
2
3
4
c1 = Candidate.new(name: "c1")
c1.save
#上面的兩步會等於下面這步
Candidate.create(name: "c1")

也就是說 create 同時新增又馬上儲存了這筆資料,如果使用 save 需要拆兩步做,update 跟 save 之間的差別也類似如此,只不過是用來更新已經存到資料庫的資料

1
2
3
4
5
6
c1 = Candidate.find_by(name: "c1")
c1.name = "qoo"
c1.save
#上面的兩步會等於下面 update 這步
c1 = Candidate.find_by(name: "c1")
c1.update(name: "qoo")

刪除資料:
這部分就比較單純,用 destroy 這個方法刊除資料庫中的資料,另外也有 destroy_bydestroy_all 可以用

c1 = Candidate.find_by(name: "c1")
c1.destroy
#找到 name 叫做 "c1" 的第一筆資料然後刪除
Candidate.destroy_by(name: "c1")
#刪除所有 name 叫做 "c1" 的資料
Candidate.destroy_all
#刪除所有 Candidate 的資料

下一篇預計會從 Layouts and Rendering in Rails 這裏繼續探討,為什麼會這樣跳著講呢?因為我覺得要對 MVC 這三個區塊分別有初步認識之後再進去看更細的章節才能把握到 rails 架構大致上的形狀,那就明天見了!

參考資料
Rails Guide





prevent_hack