user3642411 user3642411 - 1 month ago 13
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

Person
:

Person.name = "new name"

Person.name_was = "old name"


if i were to call
Person.changed?
it would return
["name"]
.

So my question is: can i somehow use the values from
person.changed
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
end


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

Answer

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'
person.sex = 'Female'
person.changes.each do |attribute, change|
  puts attribute
  puts change.first
  puts change.last
end

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

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