我試圖製作一個users
的備份表,名爲archived users
。它通過散列當前用戶屬性(self)並在self.id
中合併爲user_id
來創建ArchivedUser。爲ArchivedUser創建或更新記錄
當用戶恢復時,他們的記錄仍然保留在ArchivedUser
表中。如果用戶第二次被刪除,它應該更新任何已更改的屬性。
目前,它拋出一個驗證錯誤: Validation failed: User has already been taken
,因爲self.id
在ArchivedUser
表已經存在。
什麼是更好的方法來處理更新現有對象的對象(如果可能),或創建新記錄(如果它不存在)。我使用的軌道4,並且試圖find_or_create_by
但它拋出一個錯誤
Mysql2::Error: Unknown column 'device_details.device_app_version'
這是奇怪的,因爲該列兩個表中存在並且沒有得到修改。
用戶刪除方法
# creates ArchivedUser with the exact attributes of the User
# object and merges self.id to fill user_id on ArchivedUser
if ArchivedUser.create!(
self.attributes.merge(user_id: self.id)
)
謝謝你帶吧!