Counter cache cross settings in Ruby on Rails

69 views Asked by At

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,

1

There are 1 answers

1
taras On

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