Using a rails console I create a Model record, then retrieve using a new variable and update some fields:
var = MyModel.new
var.name = "my name"
var.save
var2 = MyModel.last
var2.name = "your name"
var2.save
now going back to the old variable var.save simply returns true and won’t overwrite the name field to its value: "my name"
Why’s that?
Rails Models are ‘Dirty’ by default, meaning that attribute setting functions,
attribute=(), mark the attribute as changed and tell Rails to update this attribute on the next save. This info is stored on the model, NOT in the database. Onvar.save, Rails only updates attributes it knows to have changed. Rails does not check the database for a discrepancy if it thinks nothing has changed (this would be incredibly slow in a production environment).You can use
var.reloadto reload attributes from the database into the corresponding object.EDIT: To clarify the comments being made above, you should be using
MyModel.lastnotMyModel.firstin your test code. If you have more than one row in your database,MyModel.firstwill not refer to the most recently saved object, and thereforevar2andvarwill refer to completely different objects.