【问题标题】:Heroku Postgres Error: Column does not existHeroku Postgres 错误:列不存在
【发布时间】:2012-05-07 20:07:00
【问题描述】:

我在部署到 heroku(运行 PG)后出现以下错误,但它在本地(运行 sqlite3)中运行良好

ActionView::Template::Error (PGError: ERROR:  column "calendar_day" does not exist
LINE 1: ...ated_at > '2012-04-09 19:39:54.787077') AND (date(calendar_d...
                                                         ^
SELECT  date(created_at) as calendar_day, count(*) as total_checkins FROM "checkins"  WHERE (user_id = 1 AND group_id = 1 AND created_at > '2012-04-09 19:39:54.787077') AND (date(calendar_day) = '2012-05-07') GROUP BY date(created_at) LIMIT 1):
...
app/helpers/groups_helper.rb:32:in `checkin_day'

请注意,“calendar_day”不是持久表上的实际列,而是我使用 AS 语句动态定义的列(不知道这在技术上叫什么)。相关的辅助函数如下所示。基本上,在页面顶部我调用了 calendar_view,稍后我将结果作为 checkins 参数传递给 checkin_day。正是在这个 checkin_day 调用中,我遇到了错误。知道为什么这在本地运行良好但在 heroku 中运行良好吗?

def calendar_view(member, timeperiod)
  Checkin.select("date(created_at) as calendar_day, count(*) as total_checkins").where("user_id = ? AND group_id = ? AND created_at > ?", member.member.id, member.group.id, Time.now - timeperiod.days).group("date(created_at)")
end

def checkin_day(checkins, day)
  ch = checkins.where("date(calendar_day) = ?", day).first
  return ch.total_checkins if ch
  return 0
end

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord heroku


    【解决方案1】:

    您在查询(投影)的 SELECT 部分定义的内容在评估 WHERE 子句(选择)期间不可用。您必须在那里再次定义它:

    def checkin_day(checkins, day)
      ch = checkins.where("date(created_at) = ?", day).first
      return ch.total_checkins if ch
      return 0
    end
    

    【讨论】:

    • 有没有办法重新定义而不必重新运行原始查询?当我在控制台上查看原始查询的输出时,我看到两列,一列名为“calendar_day”,另一列名为“total_checkins”。我可以在控制台的后续语句中引用这些列。如果我理解正确,这在 PG 中不起作用?
    • 我描述的是 PostgreSQL 服务器内部的查询处理。所有关系数据库服务器中的行为都是相同的。查询评估的基本步骤是:构建集合(使用连接......),选择(过滤行,即 WHERE 条件),投影(选择/重命名列)。这大致按此顺序完成(保存任何优化)。但一般来说,投影定义完全独立于选择。同样,在 ruby​​ 中对结果的处理完全独立于数据库内部的查询评估。
    • 好的,我想我明白了。控制台中的某些内容是否有效与数据库服务器的响应方式无关。我继续按照您的建议更改了 checkin_day 方法,它在 PostgreSQL 中有效。感谢您的帮助!
    猜你喜欢
    • 2021-10-22
    • 2019-01-16
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2015-08-29
    • 2021-09-18
    • 2012-03-19
    • 2018-09-01
    相关资源
    最近更新 更多