如何在Rails中完全删除模型及其关联? 关于异常的`schema.rb`行为关于实现此目的的更清洁方式

问题描述

说明

我正在使用 Ruby 2.6.6 Ruby on Rails 6.0.3.2

模型

  1. 作者

协会

一本书属于作者。
作者有很多书。

目标

删除作者模型,并将其作为列添加图书(类型为字符串)。

我做了什么

我按照以下顺序创建并运行了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",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",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",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列,但是我不知道这是否会...

  1. ...解决此问题并完全删除旧的Author模型,
  2. ...这是干净/推荐的处理方式。如果需要,我可以回滚迁移并尝试一种更好的方法

解决方法

关于异常的`schema.rb`行为

我尝试签出一个较旧的提交,但是架构文件顽固地拒绝更改。

这很不寻常。请确保使用git跟踪db/schema.rb文件。如果被跟踪,则没有理由为什么签出较旧的提交不应将其返回到较早的状态。此时,您应该能够:

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

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

关于实现此目的的更清洁方式

在编写下面的迁移之前,第一步是删除在Book类中编写的所有现有关系。例如:

# 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,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