Search code examples
ruby-on-railsactiverecordmarshalling

What is the best way to store and retrieve marshaled object as attribute in db via Active Record


I have gateway_response object that represents a high level ActiveMerchant gateway response. I'd like to hang on to this object in case I need it for any issues in the future.

I'd like to store it in the DB, and have marshaled it as follows. I've overwritten the getter/setter methods to marshal on assignment and unmarshal on retrieval. This seems to work, but I imagine Active Record has a leaner way to do this:

  def gateway_response=(r)
   write_attribute(:gateway_response, Marshal.dump(r))
  end
  def gateway_response
    Marshal.load(read_attribute(:gateway_response))
  end

Solution

  • Use the serialize method.

    class Order
      # add a text column called gateway_response in the `orders` table.
      serialize :gateway_response
    end
    

    Now:

    order.gateway_response = r
    order.save
    order.gateway_response # response object