Home > Back-end >  ruby on rails how can i update enum type without db:schema:load?
ruby on rails how can i update enum type without db:schema:load?

Time:03-10

I am trying to add a new field to enum type in a Ruby on Rails model. If run db:schema:load, all my seed data is lost. The seed data is production data. If i load my production data and use db:schema:load, the new enum field i have added in my model class is loaded but all my production seed data is lost. When i reload production seed data, the new enum field is lost. How do i remedy this situation? The code for my enum is below:

 enum card_type: {
         objective_question: 'objective_question',
         objective_completion_question: 'objective_completion_question',
         feedback_question: 'feedback_question',
         engagement_question: 'engagement_question',
         quick_poll: 'quick_poll',
         nps_answer: 'nps_answer'
       }

CodePudding user response:

It means your production seed data file conflicted with your schema.rb. Regarding what you explain here

  • Your production seed data has your enum column (card_type)
  • While your db/schema.rb doesn't have it

The solution is that we update your db/schema.rb to reflect with your production seed data by using rails migration

start with bundle exec rails g migration AddCardTypeColumn, then open that migration file and add your card_type column into your db/schema.rb by:

Rails 6.1 :

add_column <your_table_models>, :card_type, :string, if_not_exists: true

Rails < 6.1:

add_column <your_table_models>, :card_type, :string unless column_exists?(<your_table_models>, :card_type)

and run your latest migration with

bundle exec rails db:migrate

Then your db/schema.rb will be updated to have that card_type for you

P/S: don't use db:schema:load if you don't want to lost all your data because that command will erase your DB and recreate all tables, indexes... without the data

CodePudding user response:

were using a gem called activerecord-postgres_enum in which we need to use a migation that has the following:

add_enum_value :card_type, "nps_answer"

given "nps_answer" is the new field to add to the enum.

  • Related