Arel的多个CTE

时间:2017-07-13 21:42:37

标签: ruby-on-rails activerecord arel

我有以下格式的SQL查询:

 with from as (#{select * query}),
 to as (#{another select *}),
 rates as (#{yet another select *})
 select rates.* from rates, from, to
 where rates.from_id = from.id and rates.to_id = to.id

如何将此转换为Arel?我查看了Arel CTE,但没有像上面的查询中那样使用多个别名的示例。

1 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

from_table = Arel::Table.new(:from)
to_table = Arel::Table.new(:to)
rates_table = Arel::Table.new(:rates)
query = rates_table.
  join(from_table).on(rates_table[:from_id].eq(from_table[:id])).
  join(to_table).on(rates_table[:to_id].eq(to_table[:id])).
  project(rates_table[Arel.star]).
  with([
    Arel::Nodes::As.new(from_table, Arel::Nodes::SqlLiteral.new("select * query")),
    Arel::Nodes::As.new(to_table, Arel::Nodes::SqlLiteral.new("another select *")),
    Arel::Nodes::As.new(rates_table, Arel::Nodes::SqlLiteral.new("yet another select *")),
  ])
puts query.to_sql

您应该使用实际的Arel查询替换Arel::Nodes::SqlLiteral.new("another select *")表达式。要从ActiveRecord关系中获取Arel查询,可以在其上调用.ast。示例:User.where(active: true).ast