I have an ActiveRecord model that has a long string field. Actually, this string represents an array which I would like to modify in-place instead of copying the entire string.
For example lets say Somemodel
has a string field array
. Then the following fails to save:
m = Somemodel.first
m.array[someindex] = somevalue
m.save
Actually, save
returns true by it seems to check that array
has the same object_id
and decides that the model has not changed and skips the roundtrip to the database.
I ended up using the following workaround:
m = Somemodel.first
a = String.new(m.array) # remember, the array is represented as a string
a[someindex] = somevalue
m.array = a
m.save
Note that m.array
has to be set after modifying its value because save
looks at value and not only object_id
.
This feels cumbersome AND requires the entire string to be copied. Not nice for large array. Can I tell save
to bypass these is-model-modified checkes without foregoing validation tests?
Perhaps this is what you are looking for: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html:
If an attribute is modified in-place then make use of [attribute_name]_will_change! to mark > that the attribute is changing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With