PostgreSQL Array column + has_many association

908 views
Skip to first unread message

Carlos Ferreira da Silva

unread,
Apr 11, 2018, 7:51:00 AM4/11/18
to Ruby on Rails: Talk
I'm trying to use an array column to crete an association between 2 models. I remember that in the past this was working, but I think something has changed and now it's not working anymore. Here is the deal:

Ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-linux]
Rails 5.1.5

app/models/user.rb
# Having the columns id, name, email
class User < ApplicationRecord
end

app/models/group.rb
# Having the columns id, name, user_ids[]
class Group < ApplicationRecord
  has_many
:users, primary_key: :user_ids, foreign_key: :id
end

And the oddest thing about this is that the following works fine:
Group.first.users

It gives me the list of the users with the ids filled on that field, but the following doesn't work:
Group.first.users.load

It gives me an empty list. And, since the load method doesn't work, I cannot do any operation like #each or #to_a.
The first command don't replace the original value by a Replaceable, the second does. Maybe we just need a ReplaceableArray or something like that, or I'm missing something here.

Can anyone help me with that?

Cesar Bejarano

unread,
Feb 2, 2019, 2:26:30 AM2/2/19
to Ruby on Rails: Talk
Hi Carlos, any clue with this? I have same problem!

Eric Anderson

unread,
Feb 4, 2019, 10:08:48 AM2/4/19
to Ruby on Rails: Talk
I don't think this is supported out-of-the-box in Rails but I did see this extension a while back that appears to add what you are looking for:


Haven't personally used it but looks promising.

Eric

Carlos Ferreira da Silva

unread,
Feb 4, 2019, 10:15:00 AM2/4/19
to Ruby on Rails: Talk
I have seen this GEM before, but I wouldn't recommend it, because it doesn't use ActiveRecord Relation, which means that it probably doesn't work with "preload".

I'm planning to add this feature to my own PostgreSQL GEM this month, so if you are still interested in this feature, keep track of the new version here:

Reply all
Reply to author
Forward
0 new messages