0

I have following models: Category, SubCategory, Product, User and CategoryPerUser.

Below is corresponding ER diagram:

enter image description here

Here is a brief explanation of what I want to achieve:

  • a product belongs to a sub_category which belongs to a category

  • a user can upload many products

  • in category_per_user, I want to keep user uploaded articles per category count

For now I wrote a method in Product model which updates CategoryPerUser.products_count whenever a user add a new product.

Is there a way to set this logic using counter-cache or counter-culture ?

Or should I change my ER ?

Thanks in advance,

Sandeep Garg
  • 1,292
  • 1
  • 13
  • 31
smndiaye
  • 438
  • 7
  • 13
  • Don't think there is an automated way, you can use `after_create -> { increase_counter }` in your Product model. – Mattia M. Jun 19 '18 at 10:26
  • Is `CategoryPerUser` a physical table in the database? What columns does it have? And how do you plan to use this table? – taras Jun 19 '18 at 10:53
  • @zanadto CategoryPerUser is a physical table. It just holds `category_id` , `user_id` and `products_count`. I just want to avoid counting a user products for a given category. – smndiaye Jun 19 '18 at 11:58
  • @user4523968 thanks. thats the way I am handling it now – smndiaye Jun 19 '18 at 12:02

1 Answers1

0

In your case, I would prefer to use a database view. If you don't store a huge amount of data in the database, this will be a pretty simple and convenient solution.

The win of this solution is that you don't have to create an extra physical table in the database and don't have to run some callback every time you create/update records.

You will have a virtual table that will be created and populated only when you refer to the corresponding model. You just need to create suitable SQL query.

To read: Using Postgres Views with Rails

taras
  • 1,239
  • 1
  • 10
  • 16
  • thanks for the tips. I won't be having lot of data. Let me give it a try and check the performance @zanadto – smndiaye Jun 20 '18 at 00:58