无法通过 created_at 选择行分组
我有桌子:
+----+----------------------+---------------------+
| id | implemented_features | created_at |
+----+----------------------+---------------------+
| 1 | 19 | 2013-07-18 04:10:12 |
| 2 | 6 | 2013-07-18 04:10:12 |
| 3 | 26 | 2013-07-19 04:10:12 |
| 4 | 11 | 2013-07-19 04:10:12 |
| 5 | 1 | 2013-07-20 04:10:12 |
+----+----------------------+---------------------+
当我直接通过 MySQL 查询时,它可以按照我的意愿完美运行
When I query this directly via MySQL it works perfectly as I want
select date(created_at) as date, sum(implemented_features) as sum from summaries group by date(created_at);
但是当我尝试将此查询转换为 ActiveRecord 语法时,它返回零.
But when I try to convert this query to ActiveRecord syntax it returns me nil.
2.0.0p0 :035 > Summary.select("date(created_at) as date, sum(implemented_features)").group("date(created_at)")
Summary Load (0.5ms) SELECT date(created_at) as date, sum(implemented_features) FROM `summaries` GROUP BY date(created_at)
=> #<ActiveRecord::Relation [#<Summary id: nil>]>
如您所见,两个示例中的最终查询是相同的.为什么它在 ActiveRecord 的情况下不起作用?
As you see, final queries are equal in both examples. Why it don't work in case of ActiveRecord?
在我的 rails 项目中使用 Rails 4.0.0、Ruby 2.0、mysql db.
Using Rails 4.0.0, Ruby 2.0, mysql db in my rails project.
推荐答案
我认为您只是对控制台输出有点困惑.
I think you're just a little confused by the console output.
你说的是:
Summary.select("date(created_at) as date, sum(implemented_features)")...
所以返回的 Summary
实例(包含在 ActiveRecord::Relation
中)没有任何通常的 Summary
属性:没有 id
、没有 created_at
、没有 implemented_featured
等.当你在 ActiveRecord 对象上调用 inspect
时,它想要向您展示对象内部的内容,这意味着它想向您展示包含的数据库属性;您的 Summary
实例没有任何常用属性,因此您会看到诸如
之类的内容.
so the returned Summary
instances (wrapped up in an ActiveRecord::Relation
) don't have any of the usual Summary
attributes: no id
, no created_at
, no implemented_featured
, etc. When you call inspect
on an ActiveRecord object, it wants to show you what's inside the object and that means that it wants to show you the contained database attributes; your Summary
instances don't have any of the usual attributes so you see things like <Summary id: nil>
.
不要害怕,您选择的值确实存在.如果你说:
Fear not, the values you selected really are there. If you say:
Summary.select(...).map(&:date)
您应该看到 date(created_at) as date
值.如果为 sum(implemented_features)
添加别名,则可以使用该别名作为方法名称来提取总和.
you should see the date(created_at) as date
values. If you add an alias for the sum(implemented_features)
then you can extract the sums by using that alias as a method name.
相关文章