无法在数据集上调用.all

时间:2014-05-01 07:37:15

标签: ruby-on-rails sequel-gem

从普通sql更改查询时遇到问题(注意:我不使用AR而是续集)

这样可行:

Post.fetch(
    "SELECT
      COUNT(*) as count, HOUR(created_at) as date, class_type
    FROM
      tours t
    WHERE
      t.created_at Between ? and ?
    GROUP BY hour(t.created_at), flavor", @range_begins, @range_ends
    ).all

它返回预期的数组。但这并不是:

Post.select("COUNT(*) as count, HOUR(created_at) as date, class_type")
    .where(created_at: @basic_range)
    .group_by("HOUR(created_at), flavor")
    .all

但是在控制台中(最后没有.all)从中生成的查询看起来很好(为了更好的阅读而格式化):

<Sequel::Mysql2::Dataset:
"SELECT
  'COUNT(*) as count, HOUR(created_at) as date, class_type'
FROM
  `posts`
WHERE
  ((`created_at` >= '2014-05-01 00:00:00') AND (`created_at` <= '2014-05-01 23:59:59')) 
GROUP BY
  'HOUR(created_at), flavor'">

添加&#34; .all&#34;最后返回一个如下所示的数组:

[#<Tour @values={:"COUNT(*) as count, HOUR(created_at) as date, class_type"=>"COUNT(*) as count, HOUR(created_at) as date, class_type"}>]
我错过了什么? 在此先感谢您的帮助

1 个答案:

答案 0 :(得分:4)

使用where函数编写查询时,最后不需要编写.all,默认情况下会提供与查询参数匹配的所有结果。你只需要这样做:

Post.select("COUNT(*) as count, HOUR(created_at) as date, class_type")
    .where(created_at: @basic_range)
    .group_by("HOUR(created_at), flavor")