ActiveRecord’s queries tricks 小記

ActiveRecord’s queries tricks 小記

原文 https://medium.com/rubyinside...html

關聯表join時使用條件

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

更好的作法sql

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

關於 merge
https://apidock.com/rails/Act...
https://api.rubyonrails.org/c...api

嵌套join的差別

  • User has_one Profile
  • Profile has_many Skills
User.joins(:profiles).merge(Profile.joins(:skills))
=> SELECT users.* FROM users 
   INNER JOIN profiles    ON profiles.user_id  = users.id
   LEFT OUTER JOIN skills ON skills.profile_id = profiles.id
# So you'd rather use:
User.joins(profiles: :skills)
=> SELECT users.* FROM users 
   INNER JOIN profiles ON profiles.user_id  = users.id
   INNER JOIN skills   ON skills.profile_id = profiles.id

內連接和外鏈接ruby

Exist query

存在和不存在ide

# 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

Subqueries 子查詢

好比查詢部分用戶(user)的帖子(post)post

很差的作法code

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

這裏的缺陷是將運行兩個SQL查詢:一個用於獲取用戶的ID,另外一個用於從這些user_id獲取帖子htm

這樣寫一個查詢就能夠了字符串

Post.where(user_id: User.created_last_month)

基礎

.to_sql 生成 SQL 語句字符串
.explain 獲取查詢分析get

Booleans

對於User.where.not(tall: true)在pg下會生成
SELECT users.* FROM users WHERE users.tall <> 't'
這返回 tall 是 false 的 記錄,不包括是null 的

包括null應該這麼寫

User.where("users.tall IS NOT TRUE")

or

User.where(tall: [false, nil])
相關文章
相關標籤/搜索