2
這讓我感到困惑不已。ActiveRecord + Pry混淆
在rake任務,我對DailyScore模型保存新的記錄用下面的代碼:
def save_record_as_daily_score_object(data)
@ds = DailyScore.where(date: data[:date]).first_or_create!
@ds.update!(data)
binding.pry
end
撬輸出如下:
[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
這到底是怎麼回事?爲什麼不能訪問我的變量屬性?實際上是否保存了記錄?
更新: 檢查在控制檯,行爲是相同的,如果我只是創建一個新的對象。我使用Padrino框架和Postgres數據庫。
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>
這是模型的問題嗎?原來這裏是遷移:
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
現在又增加了另一列日:日期 - 使用:日期,而不是:日期時間 - 檢查它是否是一個怪癖:日期時間,但行爲是一樣的。
如果你調用'@ ds.valid?' –
[18] pry(main)> @ ds.valid,會發生什麼? => true –
更新前後是@ ds.changes == []嗎? –