简体   繁体   中英

Ruby on Rails How do I cache partial data from external source in an ActiveRecord model

This is my first question, so please let me know if you feel I'm making any major/minor faux pas. Thanks.

Versions:

  • Ruby - 2.5.3
  • Rails - 5.0.3

I have an existing ActiveRecord data model. Fields in a data model have become redundant to manually update as the information is available in an API. I want to retrieve, populate, and cache some of these fields from the external API.

As most entities use the data model CRUD, I was to modify the data model to always check for the cached data, and if the TTL lapses, do a fresh pull from the API.

Is there an existing in Rails or Ruby mechanism that would allow me to do this?

There appear to be ActiveRecord validation hooks for updating, but no hooks I can use for retrieving.

I'm still new to Ruby on Rails and the results from my searching haven't been great.

Much appreciation for any help you may provide!

I was able to use the after_find hook to be able to prepopulate a result and save it if the updated time was after some configurable period. Unfortunately, this didn't scale well if I was going to do an API call for each result (cough, all of them).

I ended up creating a rake task that was run periodically that would periodically call the external API to update parts of my record's results.

This doesn't seem to qualify as an objective answer to what I was looking for, so I won't mark this as the result. Thanks for anyone who viewed and considered answering this question.

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