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

如何解决如何在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-