Is it possible to tell Rails to use a JSON column as the "backend" for a relation?
I have an Article
model, that stores comment ids inside a JSON column Article#comment_ids
:
class Article < ApplicationRecord
def comments
Comment.where(id: comment_ids)
end
end
class Comment < ApplicationRecord
end
Article.first.comment_ids
=> [1,2]
Article.first.comments
=> [#<Comment:0x00007f4d7cff7c08 id: 1>,#<Comment:0x00007f4d7cff7c08 id: 2>]
Is there any way to replace this code
def comments
Comment.where(id: comment_ids)
end
with a
has_many :comments # somehow reference #comment_ids
Background: Other parts of my application use eager loading and stuff like article.association(:comments).loaded?
. And because it's not a rails relation, this doesn't work for the comments relation.