Reputation: 157
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).
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
Upvotes: 2
Views: 4795
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
rails db:migrate
Upvotes: 1
Reputation: 4709
You should use change_column_default
method in migration file.
Generate migration file
rails g migration add_default_false_to_watchlist_for_programs
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
run rails db:migrate
Upvotes: 6