Rails: How do I unserialize from database?

Posted by Macint on Stack Overflow See other posts from Stack Overflow or by Macint
Published on 2010-06-13T10:51:30Z Indexed on 2010/06/13 11:02 UTC
Read the original article Hit count: 310

Filed under:
|
|

Hello, 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.


My Model:

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

This is what I get from the form (1 consult and 3 procedures):

{"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.

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!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby