Data formatting in rails using scopes
<p>I have three models User, Order, OrderItem</p>

<pre><code>class User &lt; ApplicationRecord
  has_many :orders
end

class Order &lt; ApplicationRecord
  belongs_to :user
  has_many :order_items
end 

class OrderItem &lt; ApplicationRecord
  belongs_to :order
end
</code></pre>

<p>OrderItem contains a field <strong>amount</strong>, i need to get total amount of an order for a particular user in the format</p>

<pre><code>{{1=&gt;23.5},{2=&gt;213.5},{5=&gt;123.5}}
</code></pre>

<p>where 1,2,3 are the order id and the corresponding value is the sum of all amount in the order item of a particular order.</p>

<p>I need this kind of data for displaying a chart using <a href="https://github.com/ankane/chartkick" rel="nofollow">chartkick</a> gem</p>

<p>where the data must be in any one of the form,</p>

<pre><code>&lt;%= pie_chart({"Football" =&gt; 10, "Basketball" =&gt; 5}) %&gt;
&lt;%= pie_chart [["Football", 10], ["Basketball", 5]] %&gt;
</code></pre>

<p>please refer <a href="https://github.com/ankane/chartkick#data" rel="nofollow">https://github.com/ankane/chartkick#data</a></p>

<p>So i need to get this kind of data.</p>

<p>I have achieved it by </p>

<pre><code>  result = User.first.orders.select("orders.id, sum(order_items.amount) as charge").left_outer_joins(:order_items)
</code></pre>

<p>where the result is <code>[{"id"=&gt;206, "charge"=&gt;240000.0}, {"id"=&gt;208, "charge"=&gt;0.0}, {"id"=&gt;210, "charge"=&gt;120000.0}]</code></p>

<p>But this can be converted to format that i have mentioned by using a loop, but i don't want this kind of solution, and i need to know is there any other straight forward approach.</p>