Search code examples
ruby-on-railsactiverecordsinatrapadrinopry

ActiveRecord + Pry confusion


This is confusing me no end.

In a rake task, I am saving new records on the DailyScore model with the following code:

def save_record_as_daily_score_object(data)
    @ds = DailyScore.where(date: data[:date]).first_or_create!  
    @ds.update!(data)
    binding.pry
end

The pry output is as follows:

[10] pry(main)> data
=> {:date=>"2015-09-02",
:mail=>-0.6,
:times=>-7.1,
:telegraph=>-2.2,
:guardian=>-4.0,
:express=>-0.1,
:independent=>-3.2,
:average=>-3.4}  

[11] pry(main)> @ds
=> #<DailyScore:0x000001098121a8
 id: 4975,
 mail: nil,
 telegraph: nil,
 times: nil,
 average: nil,
 guardian: nil,
 independent: nil,
 express: nil,
 date: nil,
 created_at: 2016-05-16 13:10:03 UTC,
 updated_at: 2016-05-16 13:10:03 UTC>

 [12] pry(main)> @ds.average
 => -3.4
 [13] pry(main)> @ds.date
  => "2015-09-02"
 [14] pry(main)> @ds.persisted?
  => true
 [15] pry(main)> DailyScore.last
=> #<DailyScore:0x000001086810d8
 id: 4975,
 mail: nil,
 telegraph: nil,
 times: nil,
 average: nil,
 guardian: nil,
 independent: nil,
 express: nil,
 date: nil,
 created_at: 2016-05-16 13:10:03 UTC,
 updated_at: 2016-05-16 13:10:03 UTC>
 [16] pry(main)> DailyScore.last.average
=> nil

What is going on here? Why can't Pry access my variable attributes? And is the record actually being saved or not?

UPDATE: Checking in the console, the behaviour is the same if I simply create a new object. I'm using the Padrino framework, and a Postgres db.

2.0.0 :001 > ds = DailyScore.new(date:"2016-01-01")
 => #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>
2.0.0 :002 > ds.date
 => "2016-01-01"
2.0.0 :003 > ds
 => #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>

Is it a problem with the model? Here is the original migration:

006_create_daily_scores.rb

class CreateDailyScores < ActiveRecord::Migration
   def self.up
     create_table :daily_scores do |t|
       t.float :average
       t.datetime :date
       t.float :express
       t.float :independent
       t.float :guardian
       t.float :telegraph
       t.float :mail
       t.float :times
       t.timestamps
     end
   end

   def self.down
     drop_table :daily_scores
   end
 end

Have now added another column day:date - using :date instead of :datetime - to check if it was a quirk with :datetime, but behaviour is the same.


Solution

  • This happens because you called attr_accessor in your model with your model attributes, which overrode default accessors provided by Rails (the accessors are called by update and new methods). Note this doc, for reference, if you do want to override accessors one day.

    Removing attr_accessor from your model will do the trick!