简体   繁体   English

Rails has_many 基于 json 数组列

[英]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:与传统的连接表相比,它们也几乎没有优势:

  • JSON/Array columns cannot be used as foreign keys. JSON/Array 列不能用作外键。 So the database can't guarentee referential integrity.所以数据库不能保证参照完整性。
  • A join table can have a highly effective compound index whereas you can have GIN indexes on a JSON/array column but you still have to traverse the whole thing to join the other table.连接表可以具有高效的复合索引,而您可以在 JSON/数组列上具有 GIN 索引,但您仍然必须遍历整个事物才能连接另一个表。
  • You're violating First normal form (1NF) by placing multiple values in a single column.通过将多个值放在单个列中,您违反了第一范式 (1NF)
  • The queries with a JSON/array column are going to be hideous and unreadable.带有 JSON/array 列的查询将是可怕的和不可读的。 Joins are also faster then you think.连接也比您想象的要快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM