ChrisJ
ChrisJ

Reputation: 2792

Get a hash of old attribute values from rails active record

I want to generically access the old attributes that have changed in a model - that is, I want to get a hash of the old attributes values. My code is interested in all attributes that have changed, which may be a different set each time it's run.

I know you can get an array of changed attribute names with

model.changed

and I know you can do

model.attribute_was

to get the old value of an attribute if you know the name, but I can't find a way to programatically combine the two or to otherwise get the set of old values

I'm using it to create news stories about objects, eg

User 'Bob' changed x from a to b

Upvotes: 0

Views: 822

Answers (1)

Matzi
Matzi

Reputation: 13925

You can use the attributes hash to generate this array:

old = model.changed.map{|attr| model.send("#{attr}_was".to_sym) }

Upvotes: 1

Related Questions