Rails has_many 基于 json 数组列

23t*_*tux 5 mysql ruby-on-rails mysql-json

是否可以告诉 Rails 使用 JSON 列作为关系的“后端”?我有一个Article模型,它将评论 id 存储在 JSON 列中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>]
Run Code Online (Sandbox Code Playgroud)

有没有办法替换这段代码

def comments
  Comment.where(id: comment_ids)
end
Run Code Online (Sandbox Code Playgroud)

与一个

has_many :comments # somehow reference #comment_ids
Run Code Online (Sandbox Code Playgroud)

背景:我的应用程序的其他部分使用急切加载之类的东西article.association(:comments).loaded?。而且因为它不是 Rails 关系,所以这不适用于 Comments 关系。