How to make a "pivot table" on Ruby on Rails?

Looking at your table and the results you're looking for, I would do it like this ( I assume it's an orders table ?)

result = []
Order.all.group_by(&:name).each do |name, orders|
  record = {}
  record["name"] = name
  orders.each do |order|
    record[order.product_id] = order.amount
  end
  result.append(record)
end 

I hope this will give you a good starting point !


First install the gem

# In your Gemfile
gem 'pivot_table'

Then in your terminal, run

bundle install

Say the model represented by your first table is Sale.

sales = Sale.all
grid = PivotTable::Grid.new do |g|
  g.source_data  = sales
  g.column_name  = :product_id
  g.row_name     = :name
end

Then you can use the other methods listed in the docs. For example

g.column_headers # ['P1', 'P2', 'P3']

Note: this is just from reading the GitHub page you linked. I've never used the gem.

Edit:

You can put the code in a module:

# lib/PivotTable
module PivotTable
  def grid(data, options = {})
    grid = PivotTable::Grid.new do |g|
      g.source_data = data
      g.column_name = options[:column_name]
      g.row_name = options[:row_name]
    end
  end
end

Then you'd call it from somewhere else with

include PivotTable

def my_method
  sales = Sale.all
  grid = grid(sales, { :row_name => :name, :column_name => :product_id })
  # do stuff
end

This way you can reuse the grid-generating code and call it with arbitrary parameters.