2016-12-22 2 views
0

Ich habe ein SQL-Ergebnis dieser Form zuordnen:mehrere SQL-Ergebniswerte auf die gleichen Schlüssel

Id Amount1 Amount2 Amount3 
1 10  10  12 
2 20  13  14 
3 30  15  15 

Ich versuche, die Id in Key und alle anderen Werte in Wert

so etwas zu speichern, :

{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}} 

Dies ist, was zur Zeit so weit ich habe:

hashn = Hash.new 

    sqlresult.each { |x| 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount1'] 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount2'] 
    hashn[x['PPS_Id']] = x['Gift_Card_Amount3'] 
} 

Ich glaube, dies überschreibt den vorherigen Wert können Sie bitte helfen.

Antwort

1

Sie können auch

So etwas wie folllowing

hashn= {} 

    sqlresult.each { |x| 
    hashn[x['PPS_Id']] = [] unless hashn[x['PPS_Id']] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount1'] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount2'] 
    hashn[x['PPS_Id']] << x['Gift_Card_Amount3'] 
    } 
ein Array an eine Raute-Taste zuweisen
0

Angenommen, Ihr Sql Ergebnis ist eine aktive Plattensammlung, sollte diese Arbeit:

required_hash = {} 
sqlresult.each do |obj| 
    required_hash[obj.id] = 
    { amount1: obj.amount1, amount2: obj.amount2, amount3: obj.amount3 } 
end 
required_hash 
Verwandte Themen