Alex
Alex

Reputation: 463

How to run a rake task every time a record in a model changes? (best practice)

I want to run a cron rake task every time a record is updated - i.e. some time after the new record is created/updated, a cron rake task will do some processing on the record and save the results.

However, this task is processor intensive and it makes sense to run it only when the record is updated by the user.

What is the best way programmatically to determine if the rake task has already processed a specific record (and the user has not changed it at all)?

I'm thinking of generating a hash for each record and using it to see if it has changed. There must be a more efficient way to perform this.

Thanks for the help, Alex

Upvotes: 0

Views: 403

Answers (1)

Michał Czapko
Michał Czapko

Reputation: 1938

I think you should use DelayedJob rather than Cron/Whenever.

Anyway, don't you think it would be better to do it in validation or as before/after save filter? If you implemented this functionality as before_save filter, then you could use dirty attributes. More about dirty attributes you can find here: http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects

Upvotes: 2

Related Questions