Ruby on rails ActiveRecord:更改现有列的默认值的最干净的方法 背景
我的数据库包含两个表,我使用Ruby on rails ActiveRecord:更改现有列的默认值的最干净的方法 背景,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我的数据库包含两个表,我使用railsgmigration创建了这两个表 一个表包含电视节目,其中有几列数据描述每个节目。其中一列称为:监视列表。我忘了将默认值:watchlist设置为false,因为每个新节目的watchlist值都应该为false。在我的前端,我希望能够将该值从false切换到true(将程序添加到监视列表的操作会将该值从false更改为true) 我试过的 我正在为我的后端使用Rails API,因此我参考了并尝试使用以下代码更改\u列\u默认值: rails chang
railsgmigration
创建了这两个表
一个表包含电视节目,其中有几列数据描述每个节目。其中一列称为:监视列表。我忘了将默认值:watchlist设置为false,因为每个新节目的watchlist值都应该为false。在我的前端,我希望能够将该值从false切换到true(将程序添加到监视列表的操作会将该值从false更改为true)
我试过的
我正在为我的后端使用Rails API,因此我参考了并尝试使用以下代码更改\u列\u默认值:
rails change_column_default :program, :watchlist, from: nil, to: false
但我犯了这个错误:
Don't know how to build task 'change_column_default' (See the list of available tasks with `rails --tasks`)
我尝试了rails--tasks
,但在生成的列表中看不到我需要什么
通过搜索其他问题,我发现,但如果不需要,我宁愿不在模型上这样做
当前(不正确)迁移<代码>:监视列表应为t。布尔值:监视列表,默认值: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
class CreatePrograms
程序模型
class Program < ApplicationRecord
has_many :comments
validates :name, :network, presence: true
end
类程序
程序序列化程序
class ProgramSerializer < ActiveModel::Serializer
attributes :id, :name, :network, :image, :watchlist
has_many :comments
end
class ProgramSerializer
问题概述
谢谢你抽出时间 您应该在迁移文件中使用
change\u column\u default
方法
rails g migration add_default_false_to_watchlist_for_programs
class AddDefaultFalseToWatchlistForPrograms < ActiveRecord::Migration
def change
change_column_default :programs, :watchlist, from: nil, to: false
end
end
change\u column\u default
方法添加到迁移文件
rails g migration add_default_false_to_watchlist_for_programs
class AddDefaultFalseToWatchlistForPrograms < ActiveRecord::Migration
def change
change_column_default :programs, :watchlist, from: nil, to: false
end
end
class AddDefaultFalseTowWatchListForPrograms
这是因为
change\u column\u default
不是rake任务
- 您需要生成一个迁移
这将生成一个迁移文件。rails g migration将\u默认值\u添加到\u监视列表\u以用于\u程序
- 然后,您需要添加一行,告诉active record在我们创建的迁移中设置默认值
change\u column\u默认值:程序,:监视列表,从:nil改为:false
- 然后您需要通过
rails db:migrate