ActiveRecord:更改现有列默认值的最简洁方法

arv*_*rus 2 ruby activerecord ruby-on-rails rails-activerecord

背景

我的数据库包含两个表,我用rails g migration.

一张表包含电视节目,其中有多列数据描述每个节目。其中一列称为:watchlist。我忘记将 :watchlist 的默认值设置为 false,因为每个新节目的监视列表值都应为 false。在我的前端,我希望能够将该值从 false 切换为 true(将程序添加到监视列表的行为会将值从 false 更改为 true)。

我尝试过的

我的后端使用 Rails API,因此我查阅了文档并尝试使用以下代码更改_column_default:

rails change_column_default :program, :watchlist, from: nil, to: false
Run Code Online (Sandbox Code Playgroud)

但得到这个错误:

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

我尝试过rails --tasks,但没有在生成的列表中看到我需要的内容。

通过搜索其他问题,我找到了这个,但如果不需要的话,我宁愿不在模型上执行此操作。

当前(不正确)的迁移。: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
Run Code Online (Sandbox Code Playgroud)

程序模型

class Program < ApplicationRecord
  has_many :comments

  validates :name, :network, presence: true

end
Run Code Online (Sandbox Code Playgroud)

程序串行器

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

  has_many :comments
end
Run Code Online (Sandbox Code Playgroud)

问题回顾

  1. 我可以从命令行更新现有表中的一列吗?
  2. 如果不是,我应该如何更改当前的代码?

感谢您的时间!

dem*_*mir 6

您应该使用change_column_default迁移文件中的方法。

  1. 生成迁移文件

    rails g migration add_default_false_to_watchlist_for_programs
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将方法添加change_column_default到迁移文件

    class AddDefaultFalseToWatchlistForPrograms < ActiveRecord::Migration
      def change
        change_column_default :programs, :watchlist, from: nil, to: false
      end
    end
    
    Run Code Online (Sandbox Code Playgroud)
  3. 跑步rails db:migrate