Mari Orozco
Mari Orozco

Reputation: 13

Group sales by the person who made them and time they were made. Rails and Postgresql

In my rails application, I have a products table and a sales table. Each sales entry has a product and an amount, so each time a sale is made, more than one entry to the sales table happens because clients usually buy more than one product. I now need a way to group all the sales entries made by the same client (the table has an associated client_id) at the same time (using the created_at column) into one big sale and pass them to an array so that I can display them.

How can I do this?

Upvotes: 0

Views: 43

Answers (1)

Hass
Hass

Reputation: 1636

May I suggest a little tweak on your current approach?

Add an orders model that groups these sales together because it makes more sense and it's a lot more "rails way" than trying to group by created_at date which might cause some bugs down the line. Here's what I suggest:

order

id
user_id

class Order < ActiveRecord::Base
  has_many :products
  belongs_to :user
end

sales

id
order_id
product_id

class Sales < ActiveRecord::Base
   belongs_to :order
end

user

class User < ActiveRecord::Base
  has_many :orders
end

This way, when you want to display all the sales grouped by the order (instead or created_at) you'll be able to loop over @user.orders

Upvotes: 1

Related Questions