我有一個龐大的資料庫產品,其中包含大量用戶組態檔;我需要對所有用戶進行回填,并為每個用戶passport_country
使用另一個屬性值更新一個屬性country
,所以我進行了遷移,見下文:
用戶表:
create_table "users", id: :serial, force: :cascade do |t|
t.string "country"
t.string "passport_country"
end
新遷移:
class CopyUsersCountryToPassportCounty < ActiveRecord::Migration[6.0]
disable_ddl_transaction!
def up
User.unscoped.where.not(country: nil).in_batches do |users|
users.update_all passport_country: users.country
sleep(0.01)
end
end
end
每次遷移新遷移時都會出現以下錯誤;有什么建議么?
錯誤:
rails aborted!
StandardError: An error has occurred, all later migrations canceled
Caused by:
NoMethodError: undefined method `country' for #<User::ActiveRecord_Relation:0x00007f97fbcf4be0>
Did you mean? count
uj5u.com熱心網友回復:
您可以直接發出單個 SQL 查詢,將當前country
列中的值復制到passport_country
列中。有了這個,您不需要從資料庫中獲取單個記錄進行更新,這將使這更快。
請注意,這將發出一條 SQL 陳述句。它不會為每個用戶創建 ActiveRecord 實體,不會運行任何回呼或驗證。它還假設country
和passport_country
都是兼容型別的常規資料庫列。
class CopyUsersCountryToPassportCounty < ActiveRecord::Migration[6.0]
disable_ddl_transaction!
def up
User.unscoped.where.not(country: nil).update_all('passport_country = country')
end
end
有關其作業原理的詳細資訊,請參閱檔案ActiveRecord::Relation#update_all
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495310.html