I am trying to create a custom hash from a table. User has many transactions. A transaction has a member_id, company_id, contributions. I am trying to create a custom hash which contains transactions(contributions) happened through a member_id to a company.
    {
    member_id: {
        company: {
            id: "",
            name: ""
        },
        transactions: [
            {
                particulars: "",
                contribution: {
                    contribution1: "",
                    contribution2: ""
                }
            }
        ]
       }
   }
I can simply use
transactions.group(:member_id, :company_id).count 
to get the count, but unable to list the transactions grouped to them(Are there any ways?). So i am grouping transaction using group_by(&:member_id) and looping through the hash to generate a hash to my requirement.
Can any one review the bellow code and suggest better way to do this?
user = User.find_by(id: 123)
return {} unless user
transactions = user.transactions
return {} unless transactions.present?
data = {}
transactions.group_by(&:member_id).each do |key, value|
  transactions = []
  company = {}
  value.each do |record|
    company['id'] = record.company_id
    company['name'] = record.company_name
    particulars = record.particulars
    contribution = {}
    contribution['contribution1'] = record.contribution1
    contribution['contribution2'] = record.contribution2
    details = { "particulars": particulars, "contribution": contribution }
    transactions << details
  end
  data[key] = { "company": company, "transactions": transactions }
end