arvidrus
arvidrus

Reputation: 157

ActiveRecord: Cleanest way to change default value of existing column

Background

My database contains two tables, which I created with rails g migration.

One table contains tv programs with several columns of data describing each program. One column is called :watchlist. I forgot to set a default value of :watchlist to false, as each new show should have a watchlist value of false. On my frontend, I want to be able to toggle this value from false to true (the act of adding a program to a watchlist changes the value from false to true).

What I've Tried

I am using a Rails API for my backend, so I consulted the documentation and tried change_column_default using this code:

rails change_column_default :program, :watchlist, from: nil, to: false

but got this error:

Don't know how to build task 'change_column_default' (See the list of available tasks with `rails --tasks`)

I tried rails --tasks but did not see what I needed in the list generated.

Searching through other questions, I found this one, but would rather not do this on the model if I don't have to.

Current (incorrect) migration. :watchlist should be t.boolean :watchlist, default: false

class CreatePrograms < ActiveRecord::Migration[6.0]
  def change
    create_table :programs do |t|
      t.string :url
      t.string :name
      t.string :network
      t.string :image
      t.boolean :watchlist

      t.timestamps
    end
  end
end

Program model

class Program < ApplicationRecord
  has_many :comments

  validates :name, :network, presence: true

end

Program serializer

class ProgramSerializer < ActiveModel::Serializer
  attributes :id, :name, :network, :image, :watchlist

  has_many :comments
end

Recap of Questions

  1. Can I update one column in an existing table from command line?
  2. If no, how should I alter my current code?

Thank you for your time!

Upvotes: 2

Views: 4795

Answers (2)

Hisham Magdy
Hisham Magdy

Reputation: 144

that is because change_column_default is not a rake task

  • you need to generate a migration rails g migration add_default_value_to_watchlist_for_programs this will generate a migration file.

  • then you need to add the line that tells active record to set a default value in the migration we have created change_column_default :programs, :watchlist, from: nil, to: false

  • then you need to run the migration by rails db:migrate

Upvotes: 1

demir
demir

Reputation: 4709

You should use change_column_default method in migration file.

  1. Generate migration file

    rails g migration add_default_false_to_watchlist_for_programs
    
  2. add change_column_default method to migration file

    class AddDefaultFalseToWatchlistForPrograms < ActiveRecord::Migration
      def change
        change_column_default :programs, :watchlist, from: nil, to: false
      end
    end
    
  3. run rails db:migrate

Upvotes: 6

Related Questions