2010-11-22 6 views
0

J'ai un modèle comme suitObtenir un hachage ordonné

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 

Quand je fais Quote.from_affiliate_id (1), je reçois le résultat suivant

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

Je veux obtenir un Hash commandé à la place . Qui devrait avoir une date comme clé et compte comme valeur. Je vous prie aider moi avec ceci. Remerciant dans une anticipation

Répondre

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

merci de Shingara beaucoup, qui a vraiment aidé – usmanali

1

Essayez

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

Création d'une table de hachage normale ne sera pas commandé:

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

contre

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