我的模型如下
class Quote < ActiveRecord::Base
named_scope :from_affiliate_id, Proc.new { |id|
{ :select => "COUNT(*) as count_all, date(created_at) as date_created_at",
:conditions => {:affiliate_id => id},
:group => "date(created_at)",
}
}
named_scope :in_dates, Proc.new {|from,to|{ :conditions => ["date(created_at) >= ? and date(created_at) <= ?",from,to]}}
belongs_to :affiliate
def self.create_quote(value = '')
return if value.nil?
quote = self.new(:affiliate_id => value)
quote.save
end
end
当我做Quote.from_affiliate_id(1)时,我得到以下结果
[#<Quote >, #<Quote >, #<Quote >, #<Quote >]
我希望得到一个有序的哈希。哪个应该有一个日期作为键并计为值。请帮帮我。感谢期待
答案 0 :(得分:1)
Quote.from_affiliate_id(1).inject({}) do |h,q|
h[q.created_at] = q.count_all
h
end
答案 1 :(得分:1)
尝试
ActiveSupport::OrderedHash[*Quote.from_affiliate_id(1).map {|q|
[q.created_at, q.count_all]
}.flatten]
不会订购创建普通哈希:
>> ActiveSupport::OrderedHash[4,3,2,1].to_a
=> [[4, 3], [2, 1]]
VS
>> Hash[4,3,2,1].to_a
=> [[2, 1], [4, 3]]