Rails - find_by_sql with heredoc 引发错误
Rails - find_by_sql with heredoc raises error
我在 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 有什么问题?
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
我在 heredoc
中有这个简单的 SQLsql = <<-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 有什么问题?
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