Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force ActiveRecord to save a model when a string field is modified in place?

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?

like image 846
Avner Avatar asked Dec 06 '11 13:12

Avner


1 Answers

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.

like image 79
Marek Příhoda Avatar answered Oct 16 '22 05:10

Marek Příhoda