Bala Karthik Bala Karthik - 1 month ago 16
Ruby Question

Data formatting in rails using scopes

I have three models User, Order, OrderItem

class User < ApplicationRecord
has_many :orders
end

class Order < ApplicationRecord
belongs_to :user
has_many :order_items
end

class OrderItem < ApplicationRecord
belongs_to :order
end


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

{{1=>23.5},{2=>213.5},{5=>123.5}}


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 https://github.com/ankane/chartkick#data

So i need to get this kind of data.

I have achieved it by

result = User.first.orders.select("orders.id, 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.

Answer

Try Below Changes inside you application:

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

2.Use Below Query for get result:

        current_user.orders.includes(:order_items).map(&:to_array) ##for single user order
                         ##OR##
        Order.all.map(&:to_array)  ##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:)

Comments