Yesterday I was trying to update some fields in my database replacing strings within them and then saving.
records = Model.all records.each do |record| record["somestring"] = otherString record.save! end
This code results in no saves to the database? Why?
From what I found searching the internet (sorry, I'm not really interested in debugging ruby to find out at this point) the assignment operator is used to figure out if a field has changed and needs saving to the database. Well, I never specifically use the assignment operator and my guess is this is why rails doesn't think it's changed.
The answer (this could likely be nicer but it's just temp code so I bruteforce'd it)
records = Model.all records.each do |record| str = record.field.dup record.field["somestring"] = otherString record.field = str record.save! end
That did the trick. It works. I would call this a bug but it's possible there was a reason for this. I'm also not certain if it's possible to set the the field to be changed without using the assignment operator.
No comments:
Post a Comment