Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use array columns v.s. associations in rails

Since Rails 4 and Postgres 9, array column is introduced. I also tried using the array column to store something like tags or categories, which I don't often change and it is used as reference / facets for searching. I asked another question previously about querying with array column, and one of the answers mentioned never to use array to store data. I was then confused why array column is created if it is suggested never to use it. So my question is

When is it considered better to use array column v.s. Model associations in Rails?

like image 390
Chris Yeung Avatar asked Jan 07 '23 22:01

Chris Yeung


1 Answers

From my experience, retrieving and manipulating data from array columns is slower. So I usually prefer associations.

  1. Having array columns you are not that flexible with querying DB.

  2. Pulling data from DB is faster with associations.

  3. What if you store book's categories in DB as array and you decide to change the name of one of categories?

    Having association it's only the change of the some Category's instance name, because it's connected to other instances (books for example) by id. With array you'll have to iterate over whole collection of books to update the category's name.

I would go with using array, json or jsonb column for storing some metadata if association is an overkill.

like image 111
Andrey Deineko Avatar answered Jan 13 '23 18:01

Andrey Deineko