【发布时间】:2020-12-04 10:24:51
【问题描述】:
说明
我正在使用 Ruby 2.6.6 版 和 Ruby on Rails 6.0.3.2 版。
型号
- 书籍
- 作者
关联
一本书属于作者。
一位作者拥有许多书籍。
目标
删除 Author 模型并将其作为列添加到 Book(字符串类型)。
我做了什么
我按以下顺序创建并运行了 3 个迁移:
AddAuthorToBooks
class AddAuthorToBooks < ActiveRecord::Migration[6.0]
def change
add_column :books, :author, :string
end
end
DropAuthors
class DropAuthors < ActiveRecord::Migration[6.0]
def change
drop_table :authors do |t|
t.string "full_name", null: false
t.timestamps null: false
end
end
end
RemoveAuthorForeignKeyFromBooks
class RemoveAuthorForeignKeyFromBooks < ActiveRecord::Migration[6.0]
def change
remove_foreign_key :books, :authors
end
end
架构
不幸的是,我在运行迁移之前没有架构。 (我尝试检查一个较旧的提交,但架构文件顽固地拒绝更改。)
这是当前版本:
ActiveRecord::Schema.define(version: 2020_08_11_125724) do
create_table "books", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "cover_url"
t.decimal "price"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "author_id", null: false
t.string "author"
t.index ["author_id"], name: "index_books_on_author_id"
end
create_table "books_genres", id: false, force: :cascade do |t|
t.integer "book_id", null: false
t.integer "genre_id", null: false
t.index ["book_id", "genre_id"], name: "index_books_genres_on_book_id_and_genre_id"
t.index ["genre_id", "book_id"], name: "index_books_genres_on_genre_id_and_book_id"
end
create_table "genres", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "reviews", force: :cascade do |t|
t.string "username"
t.decimal "rating"
t.text "body"
t.integer "book_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["book_id"], name: "index_reviews_on_book_id"
end
add_foreign_key "reviews", "books"
end
问题
author 表已被删除,add_foreign_key "books", "authors"(我认为是这样的)也已消失,但 author_id 顽固地保留在 books 表中。
此外,还有一个整数 author_id 和一个同名的索引。
我的计划
我想通过另一个迁移删除这 2 列,但我不知道这是否会......
- ...修复问题并彻底清除旧的 Author 模型,
- ...这是干净/推荐的做事方式。如果需要,我可以回滚迁移并尝试更好的方法。
【问题讨论】:
标签: ruby-on-rails ruby database database-migration rails-migrations