質問

I have a model called Client with 3 attributes: name, phone and email. At the beginin, I have an instane of Client with some values: Mark, +54261334455 and fake@client.com. Then I change these values to: Peter, +54261444444, another@mail.com but I need to persist the old values. How can I do this?

My options:

  1. create old_attr columns: name, phone, email, old_name, old_phone and old_email. I think this is an ugly solution...
  2. Use serialize to persist old data having an extra fiel only: name, phone, email and data. I think this is not a good idea since y need to manipulate old data many times.
  3. create 2 instances of Client. One with old data an other with new data adding an extra field to Client model to relate these objects. I think this is the better solution but I will need to add to much logic due split "one client" in two

better ideas to do this?

役に立ちましたか?

解決

It may be an overkill in your situation but there are some great ActiveRecord versioning tools. It will let you keep track on changes done to a specific record and even reset values to former versions.

One of the best solutions I know of is paper_trail

他のヒント

Option 4: Create a ClientHistory model that is identical to Client with the addition of a client_id column that references the appropriate Client. Then, a before_save callback could do something like this:

before_save :track_history

def track_history
    return if(new_record? || !changed?)
    old = Hash[attribute_names.map { |name| [name == 'id' ? 'client_id' : name, self.send("#{name}_was")] }]
    ClientHistory.create!(old)
end

The new_record? || !changed? could be pushed to an :if option on the before_save call of course. You might want to filter the attribute_names to leave more things out of course and you might want to only track things that have changed, both of these are pretty trivial modifications (but be careful about how you track to-nil and from-nil transitions).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top