Hi, I’m sure I’m doing something obviously incorrect here, but have
stared at it for so long I can’t seem to find it.
I want to serialize some activerecord objects as rows in a table.
Basically I can:
import_object = ImportObject.new
=> #<ImportObject id: nil, object: nil, created_at: nil, updated_at:
import_object.object = Fubar.find(32)
=> #<Fubar id: 32, name: “Fubar’d” >
=> #<ImportObject id: 2958, object: #<Fubar id: 32, name: “Fubar’d” >,
created_at: “2009-07-15 22:42:40”, updated_at: “2009-07-15 22:42:40”>
Perfect! Until I save…
io = ImportObject.find(2958)
=> #<ImportObject id: 2958, import_id: nil, object: 32, created_at:
“2009-07-15 22:42:40”, updated_at: “2009-07-15 23:10:11”>
For some reason the object is getting saved as a fixnum, and I can’t
figure out why. Any ideas?
Here’s the setup:
class CreateImportObjects < ActiveRecord::Migration
create_table :import_objects do |t|
t.string :object, :limit => 512
class ImportObject < ActiveRecord::Base
One last thing:
- You will need to put the "requires " Anyplace you de-
serialize, this could include a controller unless you like in this
import = Import.find(session[:import_id])
@collection = import.objects
import_object = @collection.first
@headers = @collection.first.class.import_headers
Without the requires statement the “puts” give this:
So calling any Fubar functions on the de-serialized object will fail.
Add the “requires” and expected behavior results:
Hopefully done with this
Upon closer review… and a weekend to clear my head…
This approach was just flat wrong. Don’t even think of serializing
activeRecords. It causes all sorts of problems, some you will see,
some will be beneath the water line.
I found memcached and after reading about it, it is exactly what I’m
Solution found for posterity:
In order to serialize active records I had to do two things:
- Wrap the object in an array (import_object.object = [fubar])
The problem here, after a save, I was getting a yaml record returned
instead of a de-serialized object. After much poking around I found
this excellent article explaining that somehow custom classes
(including models it seems) were not in scope:
In the comments someone made the insightful recommendation to require
the object being serialized in the class doing the serialization.
- So, I included a requires statement for any class that I want to
serialize. (require “Fubar” in the example below).
Hope this saves someone some time!