ruby-on-rails - 未从 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:基于这个解决方案,我检查了脚本名称是否是唯一的。
解决方案
我能够通过运行以下命令来解决您的问题。我在这里找到了答案。
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.rb
so 中添加行,有关序列的信息将存储在structure.sql
. 请查看默认模式转储:ruby
有关 seqeunce 的信息未存储在schema.rb
文件中。
重要提示:确保首先使用创建structure.sql
然后rails db:migrate
运行rails db:reset
。之后rails db:migrate
我仍然收到您要修复的错误。
推荐阅读
- c# - 重启游戏后如何修复时间?
- javascript - Internet Explorer 处理数字输入的解决方法
- strapi - 如何在strapi中创建一个相似的系统
- vue.js - 无法将道具传递给根 vue 组件
- cocoa - NSCalendar 是 GUI 控件吗?
- python - 获取特定表的所有数据库名称并对每个结果运行查询
- here-api - 在这里按县搜索 api 没有经纬度
- apache-spark - 如何将 txt 文件转换为 parquet 文件并将其加载到 hdfs table-pyspark
- python - 如何使用 2 y 缩放轴和共享 X 轴进行绘图?
- node.js - 如何创建 app.use() 将数据库中的数据附加到 res 对象