我是新来的,并且很难将复杂的Postgres查询转换为Ruby。这是查询:
SELECT date_part('year', p.created_at) AS anio,
date_part('month'::text, p.created_at) AS mes,
p.id_pais, pa.nombre AS nombre_pais,
pr.id_region, re.nombre AS nombre_region,
co.id_provincia, pr.nombre AS nombre_provincia,
p.id_comuna, co.nombre AS nombre_comuna,
p.id_tipo_propiedad, p.id_modalidad,
count(*) AS total_propiedades,
sum((p.precio/mo.conversion_dolar)/p.dimension_propiedad) AS suma_precio_m2_dolar,
sum((p.precio/mo.conversion_dolar)/p.dimension_propiedad)/count(*) AS promedio_precio_m2_dolar
FROM propiedad AS p
INNER JOIN monedas AS mo ON (p.id_moneda = mo.id)
INNER JOIN comuna AS co ON (p.id_comuna = co.id)
INNER JOIN provincia AS pr ON (co.id_provincia = pr.id)
INNER JOIN region AS re ON (pr.id_region = re.id)
INNER JOIN pais AS pa ON (p.id_pais = pa.id)
WHERE p.id_modalidad IS NOT NULL
AND p.created_at IS NOT NULL
AND p.precio > 1
AND p.dimension_propiedad > 1
GROUP BY date_part('year',p.created_at), date_part('month'::text, p.created_at), p.id_tipo_propiedad,
p.id_modalidad, p.id_pais, pr.id_region, co.id_provincia, p.id_comuna, pa.nombre, re.nombre, pr.nombre, co.nombre
如果你可以帮助我,我会很感激。
答案 0 :(得分:0)
我只是将这样的东西留作普通的SQL并将其交给select_rows
:
connection.select_rows(%q{
-- your big pile of SQL goes here
}).each do |row|
# row will be an array of Strings in here
end
你必须自己解决问题,但这不应该非常困难。您也可以使用execute
:
rows = connection.execute(%q{
-- SQL goes here...
})
rows.each do |row|
# row will be a hash
end
您的查询正在从数据库中提取一些与任何特定模型不对应的数据,因此尝试使ActiveRecord生成该SQL并没有多大意义。如果查询正在生成模型,那么您将使用Model.find_by_sql
(并且仍然避免试图说服ActiveRecord生成您正在使用的SQL)。