の配列のキーを組み合わせて、私はそうのようなorganisation_id
でグループ化されたハッシュの配列を作成するために、私のクエリの結果をマップ:はハッシュ
results.map do |i|
{
i['organisation_id'] => {
name: capability.name,
tags: capability.tag_list,
organisation_id: i['organisation_id'],
scores: {i['location_id'] => i['score']}
}
}
はcapability
は、マップ外で定義されています。配列内の別のエントリがあるすべてのorganisation_id
については
[{1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{26=>4}}}, {1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{12=>5}}}, {2 => {...}}...]
:よう
結果が見えます。
Valuation.joins(:membership)
.where(capability: capability)
.select("valuations.id, valuations.score, valuations.capability_id, valuations.membership_id, memberships.location_id, memberships.organisation_id")
.map(&:serializable_hash)
Valuation
モデル:私は、次のARを使用results
を作成するには
[{1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{26=>4, 12=>5}}}, {2=>{...}}... ]
EDIT
:私はこれらのハッシュをマージし、そのようscores
キーを組み合わせるしたいと思います:
class Valuation < ApplicationRecord
belongs_to :membership
belongs_to :capability
end
Membership
モデル:
class Membership < ApplicationRecord
belongs_to :organisation
belongs_to :location
has_many :valuations
end
results
はスニペット:
[{"id"=>1, "score"=>4, "capability_id"=>1, "membership_id"=>1, "location_id"=>26, "organisation_id"=>1}, {"id"=>16, "score"=>3, "capability_id"=>1, "membership_id"=>2, "location_id"=>36, "organisation_id"=>1}, {"id"=>31, "score"=>3, "capability_id"=>1, "membership_id"=>3, "location_id"=>26, "organisation_id"=>2}, {"id"=>46, "score"=>6, "capability_id"=>1, "membership_id"=>4, "location_id"=>16, "organisation_id"=>2}...
なぜ回答を選択するのが急いでいるのですか? –
'results'の例を挙げれば、あなたの質問は大幅に改善されます。 –
Cary、最新の編集を参照してください –