【问题标题】:Getting error "function week(timestamp without time zone) does not exist"收到错误“功能周(没有时区的时间戳)不存在”
【发布时间】:2014-04-05 03:32:42
【问题描述】:

我按照这个例子How do I change the records being displayed on the page with buttons on the page (RoR) 并设法让每日过滤器工作,但是当尝试为每周过滤器设置它时,我得到了错误 PG::Error: ERROR: function week(timestamp without time zone) 不存在

我认为 WEEK 函数应该像 DATE 函数一样自动工作,但事实并非如此。

型号

def self.popularToday
    reorder('votes desc').find_with_reputation(:votes, :all, { :conditions => ["DATE(microposts.created_at) = DATE(NOW())"]})
end
def self.popularWeekly
    reorder('votes desc').find_with_reputation(:votes, :all, { :conditions => ["WEEK(microposts.created_at) = WEEK(NOW())"]})
end

index.html.erb

<form action="" method="get">
  <fieldset>
     <button type="submit" name="show" value="daily">Today</button>
     <button type="submit" name="show" value="weekly">This week</button>
  </fieldset>
</form>

控制器

when "daily"
          Kaminari.paginate_array(Micropost.popularToday).page(params[:page]).per(25)
when "weekly"
          Kaminari.paginate_array(Micropost.popularWeekly).page(params[:page]).per(25)

【问题讨论】:

    标签: sql date ruby-on-rails-4


    【解决方案1】:

    你需要:

    "SELECT EXTRACT(WEEK FROM TIMESTAMP  microposts.created_at)"
    

    这将根据 postgres 中创建的时间戳检索周数。

    文档:http://www.postgresql.org/docs/9.3/static/functions-datetime.html

    【讨论】:

    • 感谢您的建议。我尝试将其更改为此 SELECT EXTRACT(WEEK FROM TIMESTAMP 'microposts.created_at') 但现在我收到错误“PG::Error: ERROR: invalid input syntax for type timestamp:”microposts.created_at""
    • microposts.created_at 周围不应有引号。只有 sql 语句本身应该在引号内。
    • 当我删除引号时,我得到了一个语法错误,但我终于弄明白了。您的原始格式让我感到困惑,因为我尝试构建的条件有两个方面。这给了我正确的结果"EXTRACT(WEEK FROM microposts.created_at) = EXTRACT(WEEK FROM now())"
    【解决方案2】:

    具有我的时间戳但没有时区数据的表的名称称为 create_date。我使用了 EXTRACT(WEEK FROM create_date) 并且成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多