gpt4 book ai didi

ruby-on-rails - 如何对 add_column 进行可逆迁移

转载 作者:行者123 更新时间:2023-12-03 21:48:56 24 4
gpt4 key购买 nike

此迁移工作完美

class CreateCourses < ActiveRecord::Migration[6.0]
def change
create_table :courses do |t|
t.references :user, null: false, foreign_key: true
t.string :title, limit: 500, null: false
end
reversible do |dir|
dir.up do
add_column :users, :courses_count, :integer, null: false, default: 0
end
dir.down do
remove_column :users, :courses_count
end
end
end
end
但是当我运行它时它添加了courses_count但它没有在 rails db:rollback上删除它. def change 不是可逆迁移的重点吗?反转的方法 add_column ?
class CreateCourses < ActiveRecord::Migration[6.0]
def change
create_table :courses do |t|
t.references :user, null: false, foreign_key: true
t.string :title, limit: 500, null: false

add_column :users, :courses_count, :integer, null: false, default: 0
end
end
end

% rails db:migrate
== 20200815181736 CreateCourses: migrating ====================================
-- create_table(:courses)
-- add_column(:users, :courses_count, :integer)
-> 0.0037s
-> 0.0258s
== 20200815181736 CreateCourses: migrated (0.0259s) ===========================

% rails db:rollback
== 20200815181736 CreateCourses: reverting ====================================
-- drop_table(:courses)
-> 0.0060s
== 20200815181736 CreateCourses: reverted (0.0078s) ===========================

% rails db:migrate
== 20200815181736 CreateCourses: migrating ====================================
-- create_table(:courses)
-- add_column(:users, :courses_count, :integer)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DuplicateColumn: ERROR: column "courses_count" of relation "users" already exists

最佳答案

add_column needs to be outside create_table堵塞

def change
create_table :courses do |t|
t.references :user, null: false, foreign_key: true
t.string :title, limit: 500, null: false
end

add_column :users, :courses_count, :integer, null: false, default: 0
end

关于ruby-on-rails - 如何对 add_column 进行可逆迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63442185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com