简体   繁体   中英

Pub/Sub for Postgres JSON field in Rails

I have a field called data on a model called Quote. The column type is a JSON object that stores various fields which may refer to other fields. 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. 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? 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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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