首页 > 解决方案 > 未从 rspec 执行迁移

问题描述

我创建了以下迁移脚本(使用bundle exec rails generate migration CreateSequenceStudentId):

class CreateSequenceStudentId < ActiveRecord::Migration[6.0]
  def change
    # Based on: https://schmijos.medium.com/execute-sql-in-rails-migrations-cdb26f51c683
    execute 'CREATE SEQUENCE IF NOT EXISTS student_id;'
  end
end

然后执行bundle exec rails db:migrate RAILS_ENV=test并完成。我可以使用psql student_test -c"select nextval('student_id')". 最后运行psql student_test -c"select * from schema_migrations sm"列表20201122013457。到目前为止没有问题。

然后我编写了以下规范来访问该序列:

sql = "select nextval('student_id')"
p Student.connection.select_all(sql)

它失败了:

# --- Caused by: ---
# PG::UndefinedTable:
#   ERROR:  relation "student_id" does not exist
#   LINE 1: select nextval('student_id')

我又执行psql student_test -c"select nextval('student_id')"了一次并得到:

ERROR:  relation "student_id" does not exist
LINE 1: select nextval('student_id')

bundle exec rails db:migrate:status RAILS_ENV=test给出:

 Status   Migration ID    Migration Name
--------------------------------------------------
...
   up     20201122013457  Create sequence student

所以它表示迁移成功执行。

psql student_test -c"select * from schema_migrations sm"给出:

    version
----------------
 20201122013457
 20191209013052
 20191220005953
 20191225001051
 20191225001255
 20191225001458
 ...

新脚本首先执行。这闻起来很腥。

听起来迁移在使用时成功运行,db:migrate但在运行 rspec 时没有。感谢任何关于我可能做错的指示。

PS:基于这个解决方案,我检查了脚本名称是否是唯一的。

标签: ruby-on-railsactiverecordrspec

解决方案


我能够通过运行以下命令来解决您的问题。我在这里找到了答案。

RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate

更新:

我还找到了修复rails db:reset命令的方法,您只需要config.active_record.schema_format = :sql在您的application.rbso 中添加行,有关序列的信息将存储在structure.sql. 请查看默认模式转储:ruby有关 seqeunce 的信息未存储在schema.rb文件中。

重要提示:确保首先使用创建structure.sql然后rails db:migrate运行rails db:reset。之后rails db:migrate我仍然收到您要修复的错误。


推荐阅读