简体   繁体   English

Rails中Postgres JSON字段的发布/订阅

[英]Pub/Sub for Postgres JSON field in Rails

I have a field called data on a model called Quote. 我在名为Quote的模型上有一个名为data的字段。 The column type is a JSON object that stores various fields which may refer to other fields. 列类型是一个JSON对象,它存储可能引用其他字段的各种字段。 I need to keep these related fields as well as other models in sync. 我需要使这些相关字段以及其他模型保持同步。

For example, anytime income.residential_income.total or income.commercial_income.total is updated, income.total needs to be updated. 例如,随时更新income.residential_income.totalincome.commercial_income.total时 ,需要更新income.total Should the back-end update all related fields? 后端是否应该更新所有相关字段? Does it make sense for the front-end to track these changes and provide the backend with the data? 前端跟踪这些更改并向后端提供数据是否有意义? Can I use pub/sub to watch several fields on the same model in order to update these relations? 我可以使用pub / sub来监视同一模型上的多个字段以更新这些关系吗? I'm unclear what's the best simplest way to achieve this functionality. 我不清楚实现此功能的最好的最简单方法是什么。

income: {
  total: 250
  residential_income: {
    total: 100
  },

  commercial_income: {
    total: 150
  }
}

When you say PUB/SUB i assume you are talking about LISTEN/NOTIFY feature of postgres? 当您说PUB / SUB时,我假设您是在谈论postgres的LISTEN / NOTIFY功能? I would not use this for your scenario, it's easy to get out of sync when the listening process is crashed, not yet started, restarting, not reachable. 我不会在您的情况下使用它,当监听进程崩溃,尚未启动,无法重新启动,无法访问时,很容易失去同步。

Either use a trigger and update the field in the DB 使用触发器并更新数据库中的字段

or 要么

have the code that updates either of the income fields alos calculate the total. 让代码更新两个收入字段之一,然后计算总数。

or 要么

not store the total in the first place and calculate when needed 首先不存储总计,并在需要时进行计算

Since the income values are changed through the frontend, you can easily update the total at the same time. 由于收入值是通过前端更改的,因此您可以轻松地同时更新总计。 This will ensure that the values in DB are in sync with the application (important when caching) and that there is as little complexity as possible. 这将确保DB中的值与应用程序同步(在缓存时很重要),并确保尽可能少的复杂性。

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

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