Bala Karthik Bala Karthik - 2 months ago 40
Ruby Question

Data formatting in rails using scopes

I have three models User, Order, OrderItem

class User < ApplicationRecord
has_many :orders

class Order < ApplicationRecord
belongs_to :user
has_many :order_items

class OrderItem < ApplicationRecord
belongs_to :order

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


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.

I need this kind of data for displaying a chart using chartkick gem

where the data must be in any one of the form,

<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>
<%= pie_chart [["Football", 10], ["Basketball", 5]] %>

please refer

So i need to get this kind of data.

I have achieved it by

result =", sum(order_items.amount) as charge").left_outer_joins(:order_items)

where the result is
[{"id"=>206, "charge"=>240000.0}, {"id"=>208, "charge"=>0.0}, {"id"=>210, "charge"=>120000.0}]

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.


Try Below Changes inside you application:

  1. Order Model
        def to_array
          [, self.order_items.sum(:amount)]

2.Use Below Query for get result:

        current_user.orders.includes(:order_items).map(&:to_array) ##for single user order
                         ##OR##  ##for all order
  1. This will Give Result like Below ex:
        [[1, "100"]] ## id of your order and total sum of amount.

hope it will work fine:)