ActiveRecord’s queries tricks 小记原文 https://medium.com/rubyinside…关联表join时使用条件# User modelscope :activated, ->{ joins(:profile).where(profiles: { activated: true })}更好的做法# Profile modelscope :activated, ->{ where(activated: true) }# User modelscope :activated, ->{ joins(:profile).merge(Profile.activated) }关于 mergehttps://apidock.com/rails/Act…https://api.rubyonrails.org/c…嵌套join的差异User has_one ProfileProfile has_many SkillsUser.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 内链接和外连接Exist query存在和不存在# Postscope :famous, ->{ where(“view_count > ?”, 1_000) }# Userscope :without_famous_post, ->{ where(_not_exists(Post.where(“posts.user_id = users.id”).famous))}def self._not_exists(scope) “NOT #{_exists(scope)}“enddef self._exists(scope) “EXISTS(#{scope.to_sql})“endSubqueries 子查询比如查询部分用户(user)的帖子(post)不好的做法Post.where(user_id: User.created_last_month.pluck(:id))这里的缺陷是将运行两个SQL查询:一个用于获取用户的ID,另一个用于从这些user_id获取帖子这样写一个查询就可以了Post.where(user_id: User.created_last_month)基础.to_sql 生成 SQL 语句字符串.explain 获取查询分析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”)orUser.where(tall: [false, nil])