Rails 利用 Arel 联合多表查询结果

server那点事

User.from(
  Arel::Nodes::TableAlias.new(
    Arel::Table.new('users')
      .project("id, name")
      .union(Arel::Table.new('another_users').project("id, name")
    ), 'users'
  )
)

生成SQL

SELECT  "id", "name" FROM ( SELECT id, name FROM "users" UNION SELECT id, name FROM "another_users" ) "users" WHERE "users"."id" < 10

发表于 2020.06.15