0

I would like to keep a version of an object before it's updated.

For example:

This is the article on create:

#<Article:0x007fc32af4c910
 id:1,
 title: "Guitar",
 price: 300,
 buying_price: 50,
 created_at: Sun, 17 Feb 2019 14:39:21 UTC +00:00,
 updated_at: Sun, 17 Feb 2019 14:39:21 UTC +00:00,
 >

This is an update of the article:

#<Article:0x007fc32af4c910
 id:1,
 title: "Guitar",
 price: 300,
 buying_price: 35,
 created_at: Sun, 17 Feb 2019 14:39:21 UTC +00:00,
 updated_at: Mon, 18 Feb 2019 14:39:21 UTC +00:00,
 >

This the another update of the article:

#<Article:0x007fc32af4c910
 id:1,
 title: "Guitar",
 price: 380,
 buying_price: 45
 created_at: Sun,17 Feb 2019 14:39:21 UTC +00:00,
 updated_at: Wed, 20 Feb 2019 14:39:21 UTC +00:00,
 >

See the the prices have changed, but I want to be able to report them all in an accounting table:

date | buying_price | price

  • 17 feb |50 |300|

  • 18 feb |35 |300|

  • 20 feb |45 |380|

sorry I don't know how to create a table on markdown here

johan
  • 721
  • 5
  • 21

1 Answers1

2
  1. Accounting table is a DB table

    You can use previous_changes do detect what changed and in a callback to update the accounting table.

    class Article < ActiveRecord::Base
    after_save :log_to_accounting_table

     private 
    
     def log_to_accounting_table
       p previous_changes
       Accounting.create(....)
     end
    

    end

    Not related to your issue: I'm using audited to track changes.

  2. Accounting table is an Excel (what OP really wanted)

    You'll need a table to store all those changes, "old versions" as you call them. audited will help you. Then all you need to do is to export data from the audits table to a csv. Check this out to learn how to export to excel.

razvans
  • 3,172
  • 7
  • 22
  • 30
  • Thanks :) I am not sure to understand sorry... When I was talking about accounting table I meant a kind of excel table (not a DB table) to list my articles and their different states. I dont' understand how I will display my "old" versions and their date ( could be several) – johan Feb 20 '19 at 16:13
  • many thanks, I will look at this and come back to accept the answer :) – johan Feb 20 '19 at 22:29