English 中文(简体)
铁路 -- -- 日、时、组
原标题:rails - group by day as well as hour

我要创建每小时每个小时创建的项目数量阵列, 每天 。

我追踪人们的感受,所以我的模型叫做 TrackMood 它有一个叫做mood 的栏目和时间戳。

如果有的话

TrackMood.where(mood: "good").group("hour(created_at)").count

I get something like {11=>4, 12=>2, 13=>2, 15=>1}

我这里有两个问题

1 如何把一天加到今天,这样它就不会仅仅把昨天11时创造的项目加到今天11时添加的项目上?

2 当一无所有时,我如何确保它上写到 0 ?

最佳回答

1) 而不是仅仅按日期的小时部分分组,而需要将相关日期的部分分组,即按小时截止的日期分组,而不列出任何比该日期更具体的具体内容。

TrackMood.where(mood: "good").group("date_format(created_at,  %Y%m%d %H )").count

2) 您总是会从此电话中拿回一个散列, 即使它找不到任何组。 如果您想要检查有多少组, 您可以在其中调用 < code>. size 或 < code>. count

问题回答

对于 PostgreSQL, 您可以使用 < a href=" http://www. plasgresql.org/docs/8.1/static/ offices- datetime.html#FUNCTOPES- DateTIME-EXTRACT" rel=" nofollow noreferrer" >date_ part

SO- post - < a href=" https://stackoverflow.com/ questions/151820511/rails-posgresql-how-to- group-queries- by- hour" >Rails & amp; Postgresql: 如何按小时分组查询?





相关问题
rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

SSL slowness in EC2

We ve deployed our rails app to EC2. In our setup, we have two proxies on small instances behind round-robin DNS. These run nginx load balancers for a dynamically growing and shrinking farm of web ...

Auth-code with A-Za-z0-9 to use in an URL parameter

As part of a web application I need an auth-code to pass as a URL parameter. I am currently using (in Rails) : Digest::SHA1.hexdigest((object_id + rand(255)).to_s) Which provides long strings like : ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签