简体   繁体   English

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

[英]Rails: How do I unserialize from database?

I am currently trying to save information for an invoice/bill. 我目前正在尝试保存有关发票/帐单的信息。 On the invoice I want to show what the total price is made up of. 我想在发票上显示总价是多少。 The procedures & items, their price and the qty. 程序和物品,价格和数量。 So in the end I hope to get it to look like this: 所以最终我希望使它看起来像这样:

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

All this information is available through the database but i want to save the information as a separate copy. 所有这些信息都可以通过数据库获得,但我想将这些信息另存为副本。 That way if the user changes the price of some procedures the invoice information is still correct. 这样,如果用户更改某些程序的价格,则发票信息仍然正确。 I thought i'd do this by serializing and save the data to a column (consult_data) in the Invoice table. 我以为我可以通过序列化并将数据保存到发票表中的一列(consult_data)来做到这一点。


My Model: 我的模特:

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

This is what I get from the form (1 consult and 3 procedures): 这是我从表格中得到的(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"}]}

My save action: 我的保存动作:

  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

It does save to the database and if I look at the entry in the console I can see that it is all there: 它确实保存到数据库,并且如果我查看控制台中的条目,我可以看到它全部存在:

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

(---The question---) But I can't seam to get back my data. (---问题---)但是我无法缝隙取回我的数据。 I tried defining a variable to the consult_data attribute and then doing "variable.consult_problem" or "variable[:consult_problem]" (also tried looping) but it only throws no-method-errors back at me. 我尝试为consult_data属性定义一个变量,然后执行“ variable.consult_problem”或“ variable [:consult_problem]”(也尝试循环),但它只会向我抛出无方法错误。

How do I unserialize the data from the database and turn it back into hash that i can use? 我如何反序列化数据库中的数据,然后将其转回可以使用的哈希值?


Thank you very much for any help! 非常感谢您的帮助!

I think you should determine class of object 我认为您应该确定对象的类别

IE: IE浏览器:

serialize :consult_data, Hash

So then 所以呢

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

etc 等等

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

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