问题
I need to integrate a Ruby on Rails application with a 3rd-party application, which will share a common PostgreSQL database. That is, both the Rails app and the 3rd-party app will be using the same PG database.
Is it possible to set a listener within the Rails app, such that an event is fired when the 3rd-party app adds, edits or deletes a database record?
For example, say I have a Book
model defined in Rails, and the 3rd-party app adds a new row in the database's Book table (not via the BooksController
).
Can the Rails application detect that a new record has been added, or that an existing record has been edited/deleted?
回答1:
I'm not used to Ruby nor PostgreSQL, but the arquitechture is much te same for this case.
I think you should use a trigger to listen the bbdd for changes: https://www.postgresql.org/docs/9.2/static/plpgsql-trigger.html
Then you can call a webservice from that PostgreSQL script to tell Rails app it has been an update:
Postgresql - detect changes and call webservice
回答2:
This is what I finally did: Use Whenever, because it integrates nicely with Capistrano and showed me how to run Rails code from within cron. My missing peace was basically
script/runner -e production 'ChangeObserver.recentchanges' which is now run every 5 minutes. The recentchanges reads the last looked-at ID from a tmp-file, pulls all new Change records which have a higher ID than that and runs the normal observer code for each record (and saves the highest looked-at ID to the tmp-file, of course).
来源:https://stackoverflow.com/questions/39586846/how-to-listen-for-database-changes-triggered-by-a-3rd-party-application