我創建了Rails的ActiveRecord的驗證,而當它被破壞,沒有記錄被保存(事實上,我相信它被保存,然後在控制檯輸出見過ROLLBACK正在做的)。ActiveRecord的驗證工作不
但是,我沒有被重定向到新窗體並顯示我添加的錯誤消息,而是被髮送到索引頁面(沒有創建新的記錄,這是正確的,但我想要其他行爲) 。我相信是一個愚蠢的事情,與回滾有關(就像記錄正在保存,這就是爲什麼我重定向到索引頁,但隨後回滾已完成 - 不知道爲什麼,也沒有記錄被保存)。任何想法如何解決這個問題?
我創建了以下驗證:
# Adds an error if the replacement date is in the future
def replacement_date_is_not_future
unless replacement_date.blank? or replacement_date <= Date.today
errors.add(:replacement_date, :date)
end
end
,並在我的模型的頭,我有以下:
validate :replacement_date_is_not_future
這是我的控制器方法:
def create
@device_replacement = DeviceReplacementForm.new(replacement_params)
if @device_replacement.save
redirect_to device_replacements_path
else
render 'new'
end
end
這是我的控制檯輸出:
Started POST "/device_replacements" for 127.0.0.1 at 2015-12-31 10:48:09 -0300
Processing by DeviceReplacementsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MbR2lXp5ujSNILEKC2ROhij3+yNpIL3ymEdZxJejSxc=", "device_replacement_form"=>{"old_esn"=>"2-3021325", "new_esn"=>"DEMO-0-648340", "replacement_date"=>"2016-01-03"}, "commit"=>"Create"}
RackCAS::ActiveRecordStore::Session Load (0.9ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."session_id" = '0ee02a1bcbc8548e172d511c02b97490' ORDER BY "sessions"."id" ASC LIMIT 1
Device Load (1.1ms) SELECT "devices".* FROM "devices" WHERE "devices"."esn" = '2-3021325' LIMIT 1
Device Load (1.6ms) SELECT "devices".* FROM "devices" WHERE "devices"."esn" = 'DEMO-0-648340' LIMIT 1
(0.3ms) BEGIN
(0.5ms) SELECT "devices"."asset_id" FROM "devices" WHERE "devices"."id" = 81265
(0.3ms) ROLLBACK
Redirected to http://localhost:3000/device_replacements
Completed 302 Found in 93ms (ActiveRecord: 14.8ms)
RackCAS::ActiveRecordStore::Session Load (1.9ms) SELECT "sessions".* FROM "sessions" WHERE "sessions"."session_id" = '0ee02a1bcbc8548e172d511c02b97490' LIMIT 1
(0.3ms) BEGIN
(0.4ms) COMMIT
我沒有看到任何記錄被保存到數據庫。行爲似乎正確。 –
但ifrent條件(@ device_replacement.save)是真實的,這就是爲什麼被重定向到索引頁面。但由於回滾沒有顯示記錄。合理? – WhomWhomWhom
您可以使用像byebug這樣的調試器。它會停止執行並讓您在創建動作中進行遊戲。 –