Home > Back-end >  Refactoring pseudo-enum models to enums
Refactoring pseudo-enum models to enums

Time:12-13

I have a model named article_status, which does nothing more than providing statuses to the articles. I want to drop this article_status table and use enum within the article model directly.

So, I've created a new migration but my problem is how to write SQL to update the columns.

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

For the SQL part, I want the equivalent of:

Article.all.each do |article|
  article.update_columns(status: article.article_status.name.parameterize.underscore)
end

In my article model:

enum status: { draft: 0, in_review: 1, reviewed: 2, published: 3, deleted: 4 }, _default: :draft

I added the enum like this.

PS: I'm using Postgres as my database.

CodePudding user response:

I would do this:

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
  • Related