Has anyone worked on adding support for many to many relations using postgres arrays to ActiveRecord

The subject line is probably a little confusing, so here is an example.

Let’s say you have a “person” model that inherits from ActiveRecord::Base.

That person has a list of “sports” that they like and “sport” is also a model inheriting from ActiveRecord::Base.

Now, since there are many people and many sports, this is a many-to-many relation and you could model it as a join table linking “person” and “sport” using a has_many_through relation.

But what I would like to do, is to have an array of “sport_ids” on the “person” object. Each id would refer to a “sport”, and you also get ordering, say if you want the first “sport_id” to point to the person’s favorite sport.

I know you can do this, by you have to do all the work yourself.

For example, if you wanted to get the sports for a person, you would write a function on “Person” like:

def sports Sport.where(id: sport_ids) end

``

Then you can do:

person.sports

``

and get an array of sport objects. The problem is you will lose the ordering of the array here, which might be something you care about. You can try and do a fancy order clause to keep the array ordering but it is a little bit messy.

But the other problem is that this is inefficient. Say you wanted to get all children and what sports they like. You can’t do something like:

Person.includes(:sports).where(“age < 18”)

``

You end up with an n+1 query problem because you are stuck doing something like:

children = Person.where(“age < 18”) children.each do |child| child.sports …

``

Furthermore, it would great to be able to do things like this:

person.sports << hockey person.sports[2] = baseball

``

Anyways, has anyone considered adding a feature like this to ActiveRecord? If not, I’m going to work on this because it would be very useful for a couple of projects that I am working. I’d greatly appreciate if someone could point me in the right direction to get more acquainted with the ActiveRecord codebase.

Thanks.

I’ve used Postgres arrays as custom associations before; I’d be willing to help with this, though I don’t have a ton of experience with the ActiveRecord codebase.