Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update serialized field without serializing

If you mark a field with "serialize", is there still a way to update the field directly, without it running through the serialization code? I have the serialization form I want, and I do not want it re-serialized.

The use-case for this is that I am writing a migration to move from YAML serialization of a data column to JSON. I have overridden the serialize method to do JSON serialization instead of YAML. In my down migration, I need to go back from JSON to YAML, and I don't want the YAML re-serialized as JSON.

like image 746
Paul Lynch Avatar asked Jun 19 '26 19:06

Paul Lynch


1 Answers

Yes, you can do this by creating your own SQL update query. A simple way to do this is with update_all.

For example, if you have a model called Ball that has a serialized attribute colors:

Ball.where(id: ball_id).update_all colors: "arbitrary string"

This will generate the following query:

UPDATE "balls" SET "colors" = 'arbitrary string' WHERE "balls"."id" = 123

Just be careful as this does not instantiate your model so it bypasses validations, filters, etc. It is equivalent to calling ActiveRecord::Base.connection.send.

like image 112
Michael Lawrie Avatar answered Jun 24 '26 09:06

Michael Lawrie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!