学习札记——ruby on rails 关于时间操作与数据查询
笔者接到一个新的需求,要做按时间和类型两种方式进行统计数据库的数据,第一个需求是俺类型统计一共有多少数据比较简单,但是按时间和类型比较麻烦,拿到这个需求,我首先想到是的ruby中的time函数,由于我必须统计五个月内的数据,每个月都有三个类型的数据,需要生成一个数组套数组的结构,下面是我的实现代码
classMetadatum<ActiveRecord::Basescope:last_n_days,lambda{|day_max,day_min,mode|where('create_date<=?ANDcreate_date>=?ANDresource_mode=?',day_max,day_min,mode)}defstatistics_scope_of_the_timearr_list=Array.newtime_max=Time.now["XX资源","YY资源","ZZ资源"].eachdo|mode|(1..5).eachdo|count_data|time_min=Time.new(time_max.year,time_max.month)arr_data=Array.newarr_data<<time_max.montharr_data<<Metadatum.last_n_days(time_max,time_min,mode).countarr_list<<arr_dataiftime_max.month-1!=0time_max=Time.new(time_max.year,time_max.month-1,Time.days_in_month(time_max.month-1))elsereturnarr_listendendendarr_listendend
主要注意的是ruby查询方法 where的使用
scope:last_n_days,lambda{|day_max,day_min,mode|where('create_date<=?ANDcreate_date>=?ANDresource_mode=?',day_max,day_min,mode)}
这句中我们可以看到使用ruby的lambda代码块双竖线内就是就是参数,而问号依次代表了每个参数。
还有一个Time类方法 第一次接触
Time.days_in_month(month)
参数写的是月份,他返回是这个月的天数,
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。