Gaston
Gaston

Reputation: 994

Rails check if variable differs from record

I want to see if my variable differs from the corresponding record in the database.I am aware of 'attribute'_changed? method, but it only works if you updated the record through the variable.

Example

user = User.first # name = bar
u.update(name: "foo")
u.name_changed? # => true

however, in this case (integration testing for example)

u = User.first # name = bar
User.first.update(name: "foo")
u.name # => 'bar'
u.name_changed? #false
u.reload
u.name_changed #false

I want to check if my variable u differs from User.first in some attribute, which wasn't change through it.

Upvotes: 0

Views: 123

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

There's nothing built in. All you can do is load another user from database and compare their attributes.

u = User.first # name = bar
User.first.update(name: "foo")
u.name # => 'bar'
u2 = User.find(u.id)
u.name == u2.name # => false

Upvotes: 1

Related Questions