我在我的一个模型上有一个范围,我使用原始SQL(Postgres)。它看起来像这样:
scope :with_rating, lambda {
select <<~SQL
sellers.*, ROUND(SUM(average_score * total_reviews) / SUM(total_reviews)) AS seller_rating, SUM(total_reviews) AS total_reviews
FROM (
SELECT
(products.meta -> 'yotpo_bottom_line' ->> 'average_score')::numeric AS average_score,
(products.meta -> 'yotpo_bottom_line' ->> 'total_reviews')::numeric AS total_reviews,
sellers.*
FROM sellers
INNER JOIN products ON products.seller_id = sellers.id
) t JOIN sellers ON sellers.id = t.id
GROUP BY sellers.id
SQL
}
但是,当我尝试使用它时,在GROUP BY
Rails添加另一行之后:
FROM "sellers" WHERE "sellers"."deleted_at" IS NULL AND "sellers"."id" = 1063 LIMIT 1;
引发:
ERROR: syntax error at or near "FROM"
LINE 11: FROM "sellers" WHERE "sellers"."deleted_at" IS NULL AND "sel...
^