Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Refactoring pseudo-enum models to enums

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading