dougiebuckets
dougiebuckets

Reputation: 2453

Ruby datetime attribute values not saving in SQLite DB

I'm trying to save Order objects with 'sale_price' (float) and 'order_date' (datetime) attributes to a SQLite DB. Everything in the logs makes it look as though both attribute types are saved properly for each Order object. However, when I check the DB, all of the Order objects 'order_date' attributes are nil. Here's the code:

response["orders"].each do |n|

        balance = n["balance"]

        sale_price = balance.to_f

        order_date = n["created_date"]

        order = Order.new(sale_price: sale_price, order_date: order_date)

        if Order.where(order_date: order_date).exists?

            puts "That order already exists in the DB"

        else

            if (order.sale_price || order.order_date) != nil 

                order.save

            else
                p "The sale price is nil"
            end

        end     

    end

Here's what a sample transaction looks like in the logs:

    Order Exists (0.9ms)  SELECT 1 AS one FROM "orders" WHERE "orders"."order_date" = '2013-12-06T15:53:36.424Z' LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "orders" ("created_at", "order_date", "sale_price", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Tue, 27 May 2014 22:59:02 UTC +00:00], ["order_date", Fri, 06 Dec 2013 15:53:36 UTC +00:00], ["sale_price", 20548.0], ["updated_at", Tue, 27 May 2014 22:59:02 UTC +00:00]]
   (3.1ms)  commit transaction

Any thoughts?

Upvotes: 1

Views: 336

Answers (2)

John Webster
John Webster

Reputation: 26

(From the John W mentioned in @dougiebuckets answer) I think what was most likely happening (and why deleting your sqlite db file worked) is that you were looking at the first records created. Since you added the order_date field to Order in a later migration, those first records would have a nil value for order_date since that field didn't exist when they were created.

I also cheated because I had access to @dougiebuckets source code. :) But this is my first SO answer, so cut me some slack. :D

Upvotes: 1

dougiebuckets
dougiebuckets

Reputation: 2453

Deleting 'development.sqlite3' and re-running my migrations fixed it (Thanks John W.)

It looks like I had already saved all of the Order objects before adding the 'order_date' attribute, so when I saved them again w/ the 'order_date' attribute I could only see the initial Order objects that didn't have it from the original save in the console. Oops.

Upvotes: 1

Related Questions