I've been hearing lately that some many-to-many and one-to-many relationships (without additional join data, eg user-membership-group) can be queried significantly faster in Postgres using array columns of id's rather than join tables see discussion for Node Postgres ORM.
For a many-to-many relationship, choosing which table (or both) to maintain the relationship arrays would depend on which direction the query goes (users<->groups would need array columns on both tables, users->tag would only require the relationship to be maintained in an array column on the users table only.
Several questions:
- Are there any gems (Rails or otherwise) that are using the new Postgres array column to maintain relationships?
- Does anyone have any benchmarks for comparing a simple join table vs array column on a bi-directional and one directional
many-to-manyrelationships? - To capture the performance improvements with Ruby, very basic functionality would look something like below. Aside from configuration for custom primary keys, method and class names, do you see any obvious improvement to be made from the code below?
```
module ArrayRelationships
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# association must be lower case, pluralized name of associated class
def array_has_many(association)
define_method(association) do
instance_name = association.singularize
class_name = instance_name.titleize
class_name.constantize.where(id: self.send("#{instance_name}_ids"))
end
end
end
end
class User << ActiveRecord::Base
include ArrayRelationships
array_has_many :tags
end
Of course, the users table would have to have the :tag_ids array field in the database. If we wanted to add the inverse relationship for Tag#users, we would simply add the db field, include ArrayRelationships, and array_has_many :users.