简体   繁体   中英

Getting an ordered hash

I have a model as follows

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

When I do Quote.from_affiliate_id(1), I get the following result

[#<Quote >, #<Quote >, #<Quote >, #<Quote >]

I want to get an ordered Hash instead. Which should have a date as a key and count as value. Please help me with it. Thanking in an anticipation

Quote.from_affiliate_id(1).inject({}) do |h,q|
  h[q.created_at] = q.count_all
  h
end

Try

ActiveSupport::OrderedHash[*Quote.from_affiliate_id(1).map {|q|
  [q.created_at, q.count_all]
}.flatten]

Creating a normal hash will not be ordered:

>> ActiveSupport::OrderedHash[4,3,2,1].to_a
=> [[4, 3], [2, 1]]

vs.

>> Hash[4,3,2,1].to_a
=> [[2, 1], [4, 3]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM