我的應用程式中的某些記錄分配了 DOI,在這種情況下不應洗掉它們。相反,他們應該改變他們的描述,并在用戶觸發他們的洗掉時被標記。我認為,在相關模型中執行此操作的方法如下:
before_destroy :destroy_validation
private
def destroy_validation
if metadata['doi'].blank?
# Delete as normal...
nil
else
# This is a JSON field.
modified_metadata = Marshal.load(Marshal.dump(metadata))
description = "Record does not exist anymore: #{name}. The record with identifier content #{doi} was invalid."
modified_metadata['description'] = description
modified_metadata['tombstone'] = true
update_column :metadata, modified_metadata
raise ActiveRecord::RecordNotDestroyed, 'Records with DOIs cannot be deleted'
end
end
這確實可以防止洗掉,但該記錄之后似乎沒有改變,而不是有修改的描述。下面是一個測驗示例:
test "records with dois are not deleted" do
record = Record.new(metadata: metadata)
record.metadata['doi'] = 'this_is_a_doi'
assert record.save
assert_raises(ActiveRecord::RecordNotDestroyed) { record.destroy! }
assert Record.exists?(record.id)
modified_record = Record.find(record.id)
puts "#{record.description}" # This is correctly modified as per the callback code.
puts "#{modified_record.description}" # This is the same as when the record was created.
end
我只能猜測 Rails 由于引發了例外而回滾update_column,盡管我可能弄錯了。我能做些什么來防止這種情況發生嗎?
uj5u.com熱心網友回復:
保存和銷毀自動包裝在事務中 https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
所以destroy失敗了,事務被回滾,你在測驗中看不到更新的列。
您可以嘗試使用after_rollback回呼https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_rollback
或者做record.destroy檢查record.errors,如果發現用手動方法更新記錄record.update_doi if record.errors.any?。
before_destroy :destroyable?
...
def destroyable?
unless metadata['doi'].blank?
errors.add('Doi is not empty.')
throw :abort
end
end
def update_doi
modified_metadata = Marshal.load(Marshal.dump(metadata))
description = "Record does not exist anymore: #{name}. The record with identifier content #{doi} was invalid."
modified_metadata['description'] = description
modified_metadata['tombstone'] = true
update_column :metadata, modified_metadata
end
提示:使用record.reload代替Record.find(record.id).
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417919.html
標籤:
上一篇:在Rails中查詢深度嵌套的關系
