惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
Recorded Future
Recorded Future
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google DeepMind News
Google DeepMind News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
Y
Y Combinator Blog
N
News | PayPal Newsroom
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Help Net Security
Help Net Security
博客园 - Franky
SecWiki News
SecWiki News
Recent Announcements
Recent Announcements
T
Troy Hunt's Blog
The Register - Security
The Register - Security
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
S
Security Affairs
博客园 - 司徒正美
S
Schneier on Security
I
InfoQ
博客园_首页
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Threat Research - Cisco Blogs
Forbes - Security
Forbes - Security
腾讯CDC
N
Netflix TechBlog - Medium
N
News and Events Feed by Topic
Cloudbric
Cloudbric
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
A
About on SuperTechFans
Engineering at Meta
Engineering at Meta
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
V
Vulnerabilities – Threatpost
C
Check Point Blog
Google DeepMind News
Google DeepMind News
Google Online Security Blog
Google Online Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cisco Blogs
Schneier on Security
Schneier on Security
O
OpenAI News
K
Kaspersky official blog

Nic Lin's Blog

謝明真 - 高效領導力的課後筆記 NFT 開發實戰!基礎智能合約入門 (3) NFT 開發實戰!基礎智能合約入門 (2) NFT 開發實戰!基礎智能合約入門 (1) 如何自我檢測 log4j CVE 漏洞 Rails 如何在資料寫入時記錄來源 IP 位置 如何經營工程師 Youtube 頻道 - Part 8 營收篇 如何經營工程師 Youtube 頻道 - Part 7 酸民文化篇 如何經營工程師 Youtube 頻道 - Part 5 設備器材篇 如何經營工程師 Youtube 頻道 - Part 4 後製剪輯篇 如何經營工程師 Youtube 頻道 - Part 3 文案企劃篇 如何經營工程師 Youtube 頻道 - Part 2 設備器材篇 如何經營工程師 Youtube 頻道 - Part 1 制訂頻道方向篇 如何經營工程師 Youtube 頻道 - Part 0 Rails 中避免 race condition 的最佳實踐(二) Rails 中避免 race condition 的最佳實踐(一) 10 分鐘整合 google sheet 做自動化開發功能週報 經營 Side Project 300 天所帶來的收穫及挑戰 我的 Youtube 影片製作流程 API 設計時必須注意的 HTTP header 底線問題 如何提升你的程式可讀性之實務技巧(三) 如何提升你的程式可讀性之實務技巧(二) 如何提升你的程式可讀性之實務技巧(一) Ruby 中使用 freeze 優化效能的時機 避免 React 中的 useEffect 無限 render 在 Rails 內輕量使用 Vue Component 的最佳實踐 如何在區域網路用 Docker 架設有 SSL 的 Gitlab 從被問到問人,那些我常問的面試問題 在已知長度情況下優化 slice 的性能 [ReactNative] 如何在 iOS APP 上主動要求用戶評分 Rails 的 scope 為什麼用 lambda? Proc 與 lambda 不同之處 淺談 Active Record 的 Lazy load 特性 Rails 專案搭配 Github Actions 進行 RSpec 自動化測試 JavaScript 中 require, import 的差別及效能 React 效能優化基本招 ES6 箭頭函式 (Arrow functions) 2 個月擁有 6000 用戶 Side project 這樣做(一) 如何讓自己成為失敗的軟體工程師 如何用 Rack::Attack 阻擋 DDOS / 惡意流量 用 OpenSSL 自簽開發用 HTTPS SSL 憑證 為機器加上登入訊息,在 ubuntu 設置登入歡迎詞 Ruby Memoization 性能優化之記憶化 淺談 SSH agent forwarding 和 proxy command 的安全風險與應用 [Rails] Service / Library / Concern 的差異 避免過度的 Defensive Programming 防禦性程式設計 1:1 攪亂器,如何用 Ruby 做可逆推序號 Rails 中的欄位及方法命名原則 [Rails] 用 puma-dev 作為本地開發伺服器 (支援 https 自簽憑證) 將 Rails 專案從手動部屬遷移使用 Capistrano 自動化部屬 工程師提昇自己的教學和簡報技術的方法 [筆記] Rails 3.2 升級 Rails 6.beta 經驗分享 Class method 氾濫帶來什麼問題 RDBMS 課程心得與筆記 常用的 Rails 開發規範 Rest-Client 如何做 Basic Authentication 驗證 [Rails] 何為 tld_lebgth? 遵循 Semantic Versioning 軟體開發語意化版本管理 請直接在 MySQL 裡面直接用 utf8mb4 取代 utf8 如何解決在 awesome print 中遇到 ActionController::Parameters unable to convert unpermitted 如何在 Mac 上升級 PostgreSQL 並遷移資料 如何解決 Mysql2::Error: Incorrect string value 讀書心得 - 「信任因子:信任如何影響大腦運作、激勵員工、達到組織目標」 我是如何寫部落格筆記的 讀書心得 - 「先問,為什麼?:顛覆慣性思考的黃金圈理論,啟動你的感召領導力」 [Rails] 解決 Reset Password 帶來的 token 洩漏問題 我的軟體工程師生涯:如何挑選適合你的公司 Rails 中的 delegate 用法 淺述 SSR SPA 優缺點 Rails 非同步工作請用 Global ID [React] Class Component 傳遞 props 的 2 種方式 好用的隱私權政策 URL 自動生成 Rails 5.1 之後的 tag helper Rails 5.2 Encrypted Credentials 最近面試被給的建議和書單 一般架構需要用到 K8S 嗎 透過 commit SHA 找 github Pull request 從零搭建,如何讓 Rails 跑在 Kubernetes(k8s)(二) 從零搭建,如何讓 Rails 跑在 Kubernetes(k8s)(一) React Stateless Functional Components 搞懂 React 中的 state 和 props 物件導向基本原則 SOLID (Ruby Sample) 在以太坊智能合約上是可以預測隨機數的 在台灣租屋必須注意的事 Rails 5 簡單雙向加解密 如何用 ABA 培養自律型員工 不要在 rake task 中定義 method, 請用 RAKE::DSL rails 非hash只想用array輸出page 如何處理陣列裡有重複的值 [Rails] 如何重設你的專案名稱 Ruby on Rails install on Mac 安裝步驟 使用 Friendly_id 與 Babosa 美化你的Rails 網址 Junior Rails 兩個月實戰心得 Devise使用Google實作登入 [iterm2] 如何新增alias 一個新鮮人找尋Rails工作的面試經驗 如何讓兩個資料表建立關聯 routing 的 namespace strong parameter user story 的格式 user story 是什麼?
[Rails] 如何漂亮寫出可維護的 query (Maintainable Rails Query)
Nic Lin · 2020-01-05 · via Nic Lin's Blog

一般來說在 Rails 開發上,Active Record 已經算是相當成熟的 ORM 來做 SQL query 的封裝

除非極其複雜的 Query 無法用 Rails 寫出來亦或是團隊每個人都是 SQL query 高手,否則建議在團隊中我都建議用比較 Rails 的風格撰寫 Query,在後續維護上除了語意化以外也較容易做測試。

畢竟要看懂不同人寫的 query 還是相對花時間的,尤其散落一地獨樹一格的 SQL Query 當資料庫版本升級時或是 Rails 升級時會是一個頭痛的問題。

這篇文章會介紹 5 個簡單的整理技巧,而技巧因實際遭遇情況複雜度循序漸進

1. Model Scope

基本上使用這個基本招保持乾淨都能夠寫出能維護的 query

# 未帶參數
scope :published, -> { where(published: true) }
  
# 帶參數
scope :created_before, ->(time) { where("created_at < ?", time) }

串接在一起打組合技

Post.published.created_before(Time.now)

scope 回傳出來的結果一定要是 Active Record Relation,因為 scope 是讓你串接 query 使用的

如果你不確定,你可以加上 .class 來進行確認,例如

Post.recent.class

# Post::ActiveRecord_Relation

在這邊新手常犯的有以下兩種錯誤

a. 把 scope 當 method 來使用
# Bad
# 不可以把 scope 當 method 使用
scope :latest, -> { order(id: :desc).first }

# Good
# 如果要用,請保持 scope 的輸出必為 ActiveRecord Relation
scope :recent, -> { order(id: :desc) }

# 並另外呼叫
Post.recent.first
b. 回傳與當前 model 無關的 relation
# Bad
# 不可以回傳與當前 model 無關的 relation
# 在 User model 中的 scope 不能回傳 Post 的 relation  
scope :famous_posts, ->(user_id) { Post.where("user_id = ? AND view_count > ?", user_id, 1_000) }

# Good
# 真的要這麼做,請拆 class method
# User model
def self.famous_posts(user_id)
  Post.where("user_id = ? AND view_count > ?", user_id, 1_000")
end

2. Relation merge

依照關連的 table 做條件篩選

以 User has one Profile 的關連來說,假設我們要知道 User 是不是 active 需要依照 profile 中的 activated 欄位來決定

可能會這樣寫

# User model
scope :activated, ->{ joins(:profile).where(profiles: { activated: true }) }

但這樣的壞處是,其實你不應該把 profile 的邏輯放在 user 裡面

更好的作法應該是分別放兩個 model 裡面單獨寫 scope 然後用 merge 來拼出 SQL 語句

# Profile model
scope :activated, ->{ where(activated: true) }

# User model
scope :activated, ->{ joins(:profile).merge(Profile.activated) }

依照關連的 table 做排序

跨表的排序也可以用 Relation#merge 來做

情境是

  • User has many Post
  • Post has many Like

如果我們要依照 User 曾經發過所有的 Post 的所有 Like 總數最高進行倒序排序,要如何做呢?

你可能會直接硬刻 SQL?

SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" INNER JOIN "likes" ON "likes"."post_id" = "posts"."id" GROUP BY "users"."id" ORDER BY count(posts.id) DESC

或是稍微拼出來?

User.joins([posts: :likes]).group(:id).order("count(posts.id) DESC")

我覺得更易維護的作法是拆 scope + merge

# Post model
scope :sort_by_likes_count, -> { joins(:likes).group(:id).order("count(posts.id) DESC") }

# User controller
User.joins(:post).merge(Post.sort_by_likes_count)

3. Exist query

這裡指的不是 .exists?

假設有一個情況是要撈出那些 Post 點閱數較低的 User,可以用 NOT EXISTS 的 query 來進行搜尋

# Post
scope :famous, ->{ where("view_count > ?", 1_000) }
# User
scope :without_famous_post, ->{
  where(_not_exists(Post.where("posts.user_id = users.id").famous))
}

def self._not_exists(scope)
  "NOT #{_exists(scope)}"
end

def self._exists(scope)
  "EXISTS(#{scope.to_sql})"
end

這是我在另一篇文章看到之前沒想過的方法,感覺可以把這些 method 拆成 concern 用 include 的方式來使用會更好些

不過也已經有人做過類似的 Gem activerecord_where_assoc

4. Subqueries

Post.where(user_id: User.created_last_month.pluck(:id))

這樣會跑出兩條 SQL,因為他會先把資料拉出來做 pluck ,將 id 塞到 array 後再進行第二條 query 的查詢

但其實可以只打一條 query

Post.where(user_id: User.created_last_month)

基本上只要確保裡面送進去的值也是 relation,就可以讓 ActiveRecord 來幫你處理

有時候拆兩條 query 甚至會比打 subquery 來的快,這部分就要看情況來做決定了,可能取決於你的 data set 大小 / index 等等

5. Query Object

通常會用到 query object 是比較複雜的查詢或排序,一般來說上述的技巧都已經夠用,可以在符合需求的情況下不把 code 搞得太複雜

然而 query object 要解決的事情會是

  1. 抽象出複雜的查詢或排序
  2. 讓複雜的 query 是可以 testable

假設我們希望有個 class 可以幫我處理好排序的 Post,而無論那個條件都必須先依照按讚數(Like) 來做排序

class OrderedPostsQuery
  SORT_OPTIONS = %w(by_date by_title).freeze

  def initialize(params = {}, relation = Post.all)
    @relation = relation.includes(:likes).extending(Scopes)
    @sort = params[:sort].presence_in(SORT_OPTIONS)
    @direction = params[:direction]
  end

  def all
    @relation = @relation.by_likes_count
    
    @relation = case @sort
                when "by_title"
                  @relation.by_title
                when "by_date"
                  @relation.by_date
                end
    
    @relation
  end

  module Scopes
    def by_title
      order(title: @direction)
    end
    
    def by_date
      order(created_at: @direction)
    end
    
    def by_likes_count
      group(:id).order("count(posts.id) DESC")
    end
  end
end

在 controller 就可以這樣呼叫,依照 title 又是按讚數最高的排序

@posts = OrderedPostsQuery.new({ sort: :by_title, direction: :desc }).all

參考資源