【问题标题】:Rails - find_by_sql with heredoc raises errorRails - 带有 heredoc 的 find_by_sql 引发错误
【发布时间】:2019-04-19 18:18:18
【问题描述】:

我在 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 有什么问题?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord heredoc find-by-sql


    【解决方案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
    

    【讨论】:

    • Omg :D 我知道这很简单 :) 谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-09-04
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多