iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
0
自我挑戰組

Junior Ruby on Rails 工程師的心得與自我挑戰 30 天 (單身狗轉移注意力之歷練)系列 第 13

[Day13] Ruby on Rails - Model 基本、Scope 與類別方法

基本觀念:
在 Rails MVC 的 M,並不是指資料庫或資料表。

慣例 - 資料表命名:
在 Rails 專案中,Model 的命名方式是大寫單數,而資料表預設為小寫複數,並且在兩個單字以上所組成時,又會使用底線隔開。
https://ithelp.ithome.com.tw/upload/images/20190914/201126560wnnfJ4Dwo.png

Scope 與類別方法:
在 Rails 專案中的商業邏輯會盡量放到 model 裡去,除了可增加程式碼的可讀性,也可以在各個地方重複使用。 在 Rails 的 Model 有提供一種 scope 的寫法可以讓你完成這件事:

module HAWB
  class Record < ApplicationRecord
    scope :can_create_exception, -> { where.not(shipment_type: :fd) }
    scope :not_draft, -> { where(draft: false) }
  end
end

上面這個範例,我們定義了兩個 scope,其實就是把要查詢的條件給包裝起來,並且另外取了一個容易記得名稱。

預設 Scope:
Rails 的 Model 還有提供 default_scope 的方法,可以幫所有的查詢都預設套上這個條件:

module HAWB
  class Record < ApplicationRecord
    default_scope { order('id DESC') }
    scope :can_create_exception, -> { where.not(shipment_type: :fd) }
    scope :not_draft, -> { where(draft: false) }
  end
end

加上 default_scope 之後,不管你想不想,所有的查詢都會冠上 order 排序。


上一篇
Ruby on Rails - Ruby 基礎,變數、常數、流程控制、迴圈
下一篇
[Day14] Ruby on Rails - Model Migration
系列文
Junior Ruby on Rails 工程師的心得與自我挑戰 30 天 (單身狗轉移注意力之歷練)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言