user3642411 user3642411 - 1 year ago 115
Ruby Question

using the _was method in rails

So i am trying to use the _was method on an attribute.
Lets say i have an object

: = "new name"

Person.name_was = "old name"

if i were to call
it would return

So my question is: can i somehow use the values from
to do something like this:

Person.changed.each do |x|
Person.x => returns undefined value for x
Person['x'] => returns new name
Person["#{'x'}_was"] => errors

Is there a way I can use the
method with the string variable from

Answer Source

I'm not quite sure what the example code is trying to achieve, but I think you are looking for the #changes method;

person = Person.create(first_name: 'John', last_name: 'Doe', sex: 'Male')
person.first_name = 'Jane' = 'Female'
person.changes.each do |attribute, change|
  puts attribute
  puts change.first
  puts change.last

# => 'first_name'
# => 'John'
# => 'Jane'
# => 'sex'
# => 'Male'
# => 'Female'

person.changes returns a hash with all the changes where; { attribute_name => [before, after] }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download