Rails:如何从数据库中反序列化?

时间:2010-06-13 10:51:30

标签: ruby-on-rails ruby serialization

我目前正在尝试保存发票/帐单的信息。在发票上我想说明总价格是由什么组成的。程序&物品,价格和数量。所以最后我希望看起来像这样:

   Consult [date] [total_price]
      Procedure_name [price] [qty]
      Procedure_name [price] [qty]
   Consult [date] [total_price]
      Procedure_name [price] [qty]
   etc...

所有这些信息都可以通过数据库获得,但我想将这些信息保存为单独的副本。这样,如果用户更改某些程序的价格,发票信息仍然是正确的。我以为我会通过序列化并将数据保存到Invoice表中的列(consult_data)来完成此操作。


我的模特:

class Invoice < ActiveRecord::Base
   ...stuff...
   serialize :consult_data
   ...
end

这是我从表格中得到的(1个咨询和3个程序):

{"commit"=>"Save draft", "authenticity_token"=>"MZ1OiOCtj/BOu73eVVkolZBWoN8Fy1skHqKgih7Sbzw=", "id"=>"113", "consults"=>[{"consult_date"=>"2010-02-20", "consult_problem"=>"ABC", "procedures"=>[{"name"=>"asdasdasd", "price"=>"2.0", "qty"=>"1"}, {"name"=>"AAAnd another one", "price"=>"45.0", "qty"=>"4"}, {"name"=>"asdasdasd", "price"=>"2.0", "qty"=>"1"}], "consult_id"=>"1"}]}

我的保存操作:

  def add_to_invoice
   @invoice = @current_practice.invoices.find_by_id(params[:id])
   @invoice.consult_data=params[:consults]
   if @invoice.save
    render :text => "I think it worked"
   else
    render :text => "I don't think it worked'"
   end
  end

它会保存到数据库中,如果我查看控制台中的条目,我可以看到它就在那里:

consult_data: "--- \n- !map:HashWithIndifferentAccess \n  consult_da..."

(---问题---) 但我无法找回我的数据。我尝试将一个变量定义为consult_data属性,然后执行“variable.consult_problem”或“variable [:consult_problem]”(也尝试循环),但它只会向我抛出无方法错误。

如何从数据库中反序列化数据并将其重新转换为可以使用的哈希?


非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我认为你应该确定对象类

IE:

serialize :consult_data, Hash

那么

invoice = Invoice.last
invoice.consult_data[:date] # will return date