我在Heredoc中有这个简单的SQL
sql = <<-SQL
SELECT SUM(price) as total_price,
SUM(distance) as total_distance,
TO_CHAR(date, 'YYYY-MM') as month
FROM Rides
WHERE user_id = #{current_user.id}
GROUP_BY month
SQL
和一个find_by_sql(sql)
通话
Ride.find_by_sql(sql).each do |row|
"#{row.month}: { total_distance: #{row.total_distance}, total_price: #{row.total_price} }"
end
并引发错误:
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "GROUP_BY"
LINE 6: GROUP_BY month
^
: SELECT SUM(price) as total_price,
SUM(distance) as total_distance,
TO_CHAR(date, 'YYYY-MM') as month
FROM Rides
WHERE user_id = 1
GROUP_BY month
如您所见,它可以很好地插值user_id,因此问题不在插值中。
如果我将此SQL作为字符串分配给变量,则可以正常工作,
str = "select sum(distance) as total_distance, sum(price) as total_price, to_char(date, 'YYYY-MM') as month from rides where user_id = #{ current_user.id } group by month"
heredoc有什么问题?
答案 0 :(得分:1)
SQL有一个GROUP BY
子句,而不是GROUP_BY
。
sql = <<-SQL
SELECT SUM(price) as total_price,
SUM(distance) as total_distance,
TO_CHAR(date, 'YYYY-MM') as month
FROM Rides
WHERE user_id = #{current_user.id}
GROUP BY month
SQL