【发布时间】:2019-08-17 23:23:18
【问题描述】:
背景
我的数据库包含两个表,我使用rails g migration 创建。
一个表包含电视节目,其中包含描述每个节目的几列数据。一列称为:watchlist。我忘记将 :watchlist 的默认值设置为 false,因为每个新节目都应该有一个 false 的监视列表值。在我的前端,我希望能够将此值从 false 切换为 true(将程序添加到监视列表的行为会将值从 false 更改为 true)。
我的尝试
我在后端使用 Rails API,所以我咨询了documentation 并尝试使用以下代码更改_column_default:
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,但在生成的列表中没有看到我需要的内容。
搜索其他问题,我找到了this one,但如果没有必要,我宁愿不在模型上这样做。
当前(不正确的)迁移。 :watchlist 应该是 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
程序模型
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
问题回顾
- 我可以从命令行更新现有表中的一列吗?
- 如果不是,我应该如何更改我当前的代码?
感谢您的宝贵时间!
【问题讨论】:
标签: ruby-on-rails ruby activerecord rails-activerecord