【问题标题】:ActiveRecord: Cleanest way to change default value of existing columnActiveRecord:更改现有列的默认值的最简洁方法
【发布时间】: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

问题回顾

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

感谢您的宝贵时间!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

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

    1. 生成迁移文件

      rails g migration add_default_false_to_watchlist_for_programs
      
    2. 在迁移文件中添加change_column_default方法

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

    【讨论】:

      【解决方案2】:

      那是因为change_column_default 不是 rake 任务

      • 您需要生成一个迁移rails g migration add_default_value_to_watchlist_for_programs 这将生成一个迁移文件。

      • 那么你需要添加告诉活动记录在我们创建的迁移中设置默认值的行 change_column_default :programs, :watchlist, from: nil, to: false

      • 那么您需要通过rails db:migrate 运行迁移

      【讨论】:

      • 出于好奇,这与之前的答案有何不同?
      猜你喜欢
      • 1970-01-01
      • 2012-11-10
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多