Home > Mobile >  Modify ActiveRecord attribute only for saving
Modify ActiveRecord attribute only for saving

Time:12-17

Lets assume I have some ActiveRecord instance. How can I get rails to map a field of it before it gets saved in the database but without changing the value of the record in memory?
before_save callback seems to modify the value not just for saving it.

This example shows the desired behavior by mapping the field n with n -> n*2 (a reversible mapper)

x = MyRecord.create(n: 2)
x.n
=> 2
x.save()   # database should now contain value 4 in col n
x.n
=> 2       # value is still 2 (map only affects values in db)

More specifically i want to use Marshal.dump & Marshal.load to (de)serialize fields of my records for the database to contain them as blobs.

CodePudding user response:

In your code, MyRecord.create(n: 2) actually will save the record to the DB.

If you want to use custom serialization (e.g. to Marshall between the storage and memory format of the field). Then you can use a custom value type, see: https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html (under Creating Custom Types).

  • Related