我有一個名為 的模型article_status,它只為文章提供狀態。我想洗掉這個article_status表并直接enum在article模型中使用。
所以,我創建了一個新的遷移,但我的問題是如何撰寫 SQL 來更新列。
class AddStatusToArticles < ActiveRecord::Migration[6.1]
def change
add_column :articles, :status, :integer
add_index :articles, :status
execute <<~SQL
# Write SQL here
SQL
change_column :articles, :status, :integer, null: false
end
end
對于 SQL 部分,我想要相當于:
Article.all.each do |article|
article.update_columns(status: article.article_status.name.parameterize.underscore)
end
在我的article模型中:
enum status: { draft: 0, in_review: 1, reviewed: 2, published: 3, deleted: 4 }, _default: :draft
我添加了enum這樣的。
PS:我使用 Postgres 作為我的資料庫。
uj5u.com熱心網友回復:
我會這樣做:
statuses = ArticleStatus
.pluck(:id, :name)
.map { |(id, name)| [id, name..parameterize.underscore] }
.to_h
Article.find_each do |article|
article.update_columns(status: statuses[article. article_status_id])
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380144.html
標籤:sql 红宝石轨道 红宝石 PostgreSQL的
