views:

54

answers:

1

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!

+1  A: 

I think you should determine class of object

IE:

serialize :consult_data, Hash

So then

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

etc

fl00r
Ok I have tried that.When I have it as "serialize :consult_data, Hash"and try to save i get this, when trying to save:"consult_data was supposed to be a Hash, but was a Array"-----Then I tried "serialize :consult_data, Array" And it works!-----And because it was an array(that could have multiple consults) I also had to define which one i wanted."invoice.consult_data[0][:consult_date] #does return the date"----YAY!Thank you very much.
Macint