[英]Rails has_many based on a json array column
Is it possible to tell Rails to use a JSON column as the "backend" for a relation?是否可以告诉 Rails 使用 JSON 列作为关系的“后端”? I have an
Article
model, that stores comment ids inside a JSON column Article#comment_ids
:我有一篇
Article
model,它将评论 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>]
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?
背景:我的应用程序的其他部分使用预加载和
article.association(:comments).loaded?
. . And because it's not a rails relation, this doesn't work for the comments relation.
而且因为它不是 rails 关系,所以这不适用于 comments 关系。
No, its not possible.不,这是不可能的。 ActiveRecord is built around the relational model with tables that related to other tables.
ActiveRecord 是围绕关系 model 构建的,表与其他表相关。 Querying JSON/JSONB/Array columns requires the use of completely different operators and they are not polyglot.
查询 JSON/JSONB/Array 列需要使用完全不同的运算符,并且它们不是多语言的。 They also have little to no advantages over a traditional join table:
与传统的连接表相比,它们也几乎没有优势:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.