如何完全删除 Rails 中的模型及其关联?

How to completely remove a model and its associations in Rails?

描述

我在 Ruby 版本 2.6.6Ruby 在 Rails 版本 6.0.3.2.

型号

  1. 图书
  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

问题

作者table被删除了,add_foreign_key "books", "authors"(我想就是这样)也不见了,但是author_id固执地留在了books table.

此外,还有一个整数author_id和一个同名索引。

我在计划什么

我想通过另一次迁移删除这两列,但我不知道那是否会...

  1. ...解决问题并完全删除旧作者模型,
  2. ...这是 clean/recommended 做事的方式。如果需要,我可以回滚迁移并尝试更好的方法。

关于异常 `schema.rb` 行为

I tried checking out an older commit, but the schema file stubbornly refuses to change.

这很不寻常。请确认您正在使用 git 跟踪 db/schema.rb 文件。如果它被跟踪,没有理由不检查旧提交 return 到旧状态。届时,您应该能够:

$ rails db:drop
$ rails db:create
$ rails db:schema:load

...将旧模式加载到数据库中。然后,您应该能够 return 使用 git 到最新代码,并且 运行 在创建旧模式的日期之后等待迁移。

关于更简洁的实现方式

在编写以下迁移之前,第一步是删除 Book class 中写入的任何现有关系。例如:

# app/models/book.rb
class Book < ApplicationRecord
  # The line below should be deleted! Otherwise, it will probably interfere
  # with the `book.update!(author: ...)` line in the migration.
  belongs_to :author
end

我已经开始在一个文件中编写相关的迁移,因为它们都是相关的。对我来说,这看起来像:

class MoveAuthorToBooks < ActiveRecord::Migration[6.0]
  class Author < ApplicationRecord
  end

  class Book < ApplicationRecord
  end

  def up
    # Start by adding a string column.
    add_column :books, :author, :string

    # Let's preserve existing author names.
    Book.all.each do |book|
      author = Author.find(book.author_id)
      book.update!(author: author.name)
    end

    # Now that the names have been moved to the books table, we don't
    # need the relationship to `authors` table anymore. This should
    # also delete any related foreign keys - manual foreign key deletion
    # should not be required.
    remove_column :books, :author_id

    # Alternative: If you'd created the `authors_id` column using the
    # `add_reference` command, then it's probably best to use the opposite
    # `remove_reference` command.
    #
    #remove_reference :books, :author, index: true, foreign_key: true


    # Finally, remove the `authors` table.
    drop_table :authors 
  end

  def down
    # This can be technically be reversed, but that'll need some more code that
    # reverses the action of the `up` function, and it may not be needed.

    raise ActiveRecord::IrreversibleMigration
  end
end