I have a model called Day that represents a day in a timesheet. I’ve noticed that whenever I call @day.save it’s writing to the database, even though none of the object’s properties have had their values changed.
@day = Day.last
=> #<Day lunch_minutes: 0, updated_at: "2012-08-19 12:09:40", work_hours: 5.5>
A day has its length in hours, and the length of its lunch break in minutes, stored. I’ve cropped out some properties that aren’t relevant.
@day.lunch_minutes
=> 0
@day.lunch_minutes = 0
=> 0
@day.changes
=> {"lunch_minutes"=>[0, 0]}
@day.lunch_minutes_changed?
=> true
That should be false. Compare to a value that isn’t zero:
@day.work_hours = 5.5
=> 5.5
@day.work_hours_changed?
=> false
So if I call save, this gets called. Ideally there would be no unnecessary database interaction here.
@day.save
(0.5ms) UPDATE "days" SET "lunch_minutes" = 0, "updated_at" = '2012-08-19 12:22:59.586860' WHERE "days"."id" = 48
I’m not sure if this is a Rails bug or if I’m doing some incorrectly somewhere. It looks like it could be an issue in “changes_from_zero_to_string?” – I think adding a && value != 0 to that method would fix it – but I want to know if anyone else has seen this/a fix for this before?
What version of rails are you using? I just had a go in my app (3.1.5/1.8.7) and it doesn’t behave this way.. I just used a random integer property on one of my models to test with: