Express a CTE using Arel

旧街凉风 提交于 2019-12-11 06:17:41

问题


I have this snippet of ActiveRecord:

scope = Listing.where(Listing.arel_table[:price].gt(6_000_000))

The resulting sql:

SELECT listings.* FROM listings where listings.price > 6000000

I would like to add a CTE that would result in this sql:

WITH lookup AS (
    SELECT the_geom FROM lookup WHERE slug = 'foo-bar'
)

SELECT * from listings, lookup
WHERE listings.price > 6000000
AND ST_within(listings.the_geom, lookup.the_geom)

I would like to express this sql inclusive of the CTE using Arel and ActiveRecord.

I would also like to use the scope variable as a starting point.


回答1:


You can create the CTE like:

lookup = Arel::Table.new(:lookup) # Lookup.arel_table
cte = Arel::Nodes::As.new(lookup,
  lookup.where(lookup[:slug].eq('foo-bar')).project('the_geom'))

and then use it with your scope like:

scope.with(cte)

You can see an example for this in the Arel README, at the very bottom



来源:https://stackoverflow.com/questions/46286924/express-a-cte-using-arel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!