简体   繁体   English

通过Active Record在db中存储和检索封送处理的对象作为属性的最佳方法是什么

[英]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. 我有gateway_response对象,它代表高级ActiveMerchant网关响应。 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. 我已经覆盖了getter / setter方法,以在分配时封送和在检索时封送。 This seems to work, but I imagine Active Record has a leaner way to do this: 这似乎可行,但我想Active Record有一种更精简的方法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM