Cheat Sheet速查表
跳转到主要内容

Arel 速查表

本文根据 Devhints / Arel 翻译。代码示例及版本范围沿用原文。

关于

Arel 是一个 SQL 抽象库,内置于 Rails 平台上的 Ruby 中。

表

users = Arel::Table.new(:users)
users = User.arel_table  # ActiveRecord model

字段

users[:name]
users[:id]

where (限制)

users.where(users[:name].eq('amy'))
# SELECT * FROM users WHERE users.name = 'amy'

select (投影)

users.project(users[:id])
# SELECT users.id FROM users

join

基本连接

在 ActiveRecord 中(不使用 Arel 时),如果 :photos 是关联名称,则使用 joins

users.joins(:photos)

在 Arel 中,如果 photos 被定义为 Arel 表,

photos = Photo.arel_table
users.join(photos)
users.join(photos, Arel::Nodes::OuterJoin).on(users[:id].eq(photos[:user_id]))

带条件的连接

users.joins(:photos).merge(Photo.where(published: true))

如果简单版本无法满足需求,且你想在其中添加更多的 SQL 语句:

users.join(
   users.join(photos, Arel::Nodes::OuterJoin)
   .on(photos[:user_id].eq(users[:id]).and(photos[:published].eq(true)))
)

高级连接

多重 joins 针对同一张表,但具有不同的含义和/或条件

creators = User.arel_table.alias('creators')
updaters = User.arel_table.alias('updaters')
photos = Photo.arel_table

photos_with_credits = photos
.join(photos.join(creators, Arel::Nodes::OuterJoin).on(photos[:created_by_id].eq(creators[:id])))
.join(photos.join(updaters, Arel::Nodes::OuterJoin).on(photos[:assigned_id].eq(updaters[:id])))
.project(photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor'))

photos_with_credits.to_sql
# => "SELECT `photos`.`name`, `photos`.`created_at`, `creators`.`name` AS creator, `updaters`.`name` AS editor FROM `photos` INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `creators` ON `photos`.`created_by_id` = `creators`.`id`) INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `updaters` ON `photos`.`updated_by_id` = `updaters`.`id`)"

# after the request is done, you can use the attributes you named
# it's as if every Photo record you got has "creator" and "editor" fields, containing creator name and editor name
photos_with_credits.map{|x|
  "#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}"
}.join('; ')

limit / offset

users.take(5) # => SELECT * FROM users LIMIT 5
users.skip(4) # => SELECT * FROM users OFFSET 4

聚合

users.project(users[:age].sum) # .average .minimum .maximum
users.project(users[:id].count)
users.project(users[:id].count.as('user_count'))

order

users.order(users[:name])
users.order(users[:name], users[:age].desc)
users.reorder(users[:age])

使用 ActiveRecord

User.arel_table
User.where(id: 1).arel

利用 Arel 编写整洁的代码

大部分巧妙的逻辑都应放在作用域(scopes)或 e.g 中。上述代码可以变为:

photos_with_credits = Photo.with_creator.with_editor

您可以将请求存储在变量中,然后添加 SQL 片段:

all_time      = photos_with_credits.count
this_month    = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month))
recent_photos = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month)).limit(5)