簡體   English   中英

Rails-使用Heredoc的find_by_sql引發錯誤

[英]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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM