我有一个脚本文件,其中包含docker compose命令
bootstrap.sh
set -e
#Building docker image
docker-compose build
#Creating Database
docker-compose run --rm app bundle exec rails db:create
#Running Migration
docker-compose run --rm app bundle exec rails db:migrate
#Seeding Database. Running this command twice will throw an error and will terminate the execution
docker-compose run --rm app bundle exec rails db:seed
#Starting Docker containers
docker-compose up
这里,bundle exec rails db:seed
命令在每个数据库中只能运行一次。当我第一次运行sh bootstrap.sh
时,它会正常工作,但sh bootstrap.sh
的后续运行将失败,因为我试图对同一数据库进行两次种子设定。
所以,即使播种失败,我也需要一种方法来返回成功,这样我的docker容器就可以了。
例如docker-compose run --rm app bundle exec rails db:seed || true
之类的。当传递给docker compose的命令失败时,是否可以返回true?
Rails还提供了一个方便的命令,用于创建、加载模式和种子数据库:db:setup
。
bin/rails db:setup命令将创建数据库,加载架构,并使用种子数据对其进行初始化。
https://edgeguides.rubyonrails.org/active_record_migrations.html#setup-数据库
在这种情况下,如果数据库已经存在,它将返回退出状态0。我认为这是一个合理的假设,当数据库存在时,我们也假设它是正确的种子。
set -e
# Building docker image
docker-compose build
# Create db, load the schema and seed it
docker-compose run --rm app bundle exec rails db:setup
# Starting Docker containers
docker-compose up
但是,如果在决定是否需要为数据库播种之前需要进行更多检查(例如查询数据库(,则可以在seeds.rb
脚本中进行检查。类似的东西
return if User.where(name: "Admin").exists? # If Admin user exists we assume DB is properly seeded
默默地接受bootstrap.sh
脚本中的错误可能不是一个好主意,在这种情况下,你应该更喜欢在seeds.rb
中有一个安全网,而不是没有错误。否则,您可能会收到损坏的数据。