ActiveRecord’s queries tricks 小记

栏目: Ruby · 发布时间: 7年前

内容简介:原文更好的做法内链接和外连接

ActiveRecord’s queries tricks 小记

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

关联表join时使用条件

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

更好的做法

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

嵌套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

内链接和外连接

Exist 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

Subqueries 子查询

比如查询部分用户(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")

or

User.where(tall: [false, nil])

以上所述就是小编给大家介绍的《ActiveRecord’s queries tricks 小记》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

世界是数字的

世界是数字的

[美] Brian W. Kernighan / 李松峰、徐建刚 / 人民邮电出版社 / 2013-6 / 49.00

家用电器、汽车、飞机、相机、手机、GPS 导航仪,还有游戏机,虽然你看不见,但这些设备都有计算能力。手机通信网络、有线电视网络、空中交通管制系统、电力系统、银行和金融服务系统等基础设施背后无一不是计算机在支撑。如今的世界是数字的,而计算机和计算无处不在。这本书就是要告诉大家数字世界有关计算机的一切。本书没有高深莫测的专业术语,但它全面解释了当今计算和通信领域的工作方式,包括硬件、软件、互联网、通信......一起来看看 《世界是数字的》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具