原文 https://medium.com/rubyinside...html
# 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
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
存在和不存在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
好比查询部分用户(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
对于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])