solefald
solefald

Reputation: 1799

Active Record: Elegant way to copy a field before update?

I have a table with a bunch of rows that i need to update (sometimes a single row, sometimes many at once). However, before updating, I would like to copy values from 2 columns to other two.

id, current_tag, current_serial, previous_tag, previous_serial

I need to copy current_tag -> previous_tag and current_serial -> previous_serial and then update current_tag and current_serial.

Is there an elegant/fast approach for doing that?

I am also not married to the idea of having previous_tag and previous_serial columns, but I do need a way to preserve previous values in case user needs to do a roll back?

Upvotes: 0

Views: 165

Answers (1)

muttonlamb
muttonlamb

Reputation: 6501

I would consider this to be a solved problem by using something like the paper_trail gem. It would provide all of the functionality you require with very elegant rollback functionality (even beyond simply the last change made, you can have a complete history).

I've found it very easy to integrate with existing apps.

It's available here https://github.com/airblade/paper_trail

I note that this isn't the only solution, there are many others here https://www.ruby-toolbox.com/categories/Active_Record_Versioning

Upvotes: 1

Related Questions