iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0
Modern Web

Rails guide / Ruby API study系列 第 6

[ Rails guide study ] Day06 如何複寫Model table 慣例 / 資料存取刪除簡介 (Active Record Basics part3)

首先來聽個歌吧
Yes
今天剛好要講到覆蓋(cover)原本的設定,所以來聽聽 2019 最夯的 cover 吧!


覆寫 model 中 table name 跟 primary key 慣例

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

self.table_name = "my_products"

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

#my_products.yml
class ProductTest < ActiveSupport::TestCase
  set_fixture_class my_products: Product
  fixtures :my_products
  ...
end

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

self.primary_key = "product_id"

資料存取與刪除

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

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

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

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

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

本文章同步分享於 http://anthonychao.site/


上一篇
[ Rails guide study ] Day05 Primary key / Foreign key介紹(Active Record Basics part2)
下一篇
[ Rails guide study ] Day07 Render 的基本使用 (Layouts and Rendering in Rails part1)
系列文
Rails guide / Ruby API study30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言