I would like to know if there is a specific command for rails db:migrate:reset.

Happy new year.
Thank you for your continued support this year.

Hi!
I would like to ask you a question.

What I want to achieve =
I was able to successfully deploy the rails application the other day, but I would like to know if the database can be reset once.
In other words, could you tell me if there is a specific command for rails db:migrate:reset, rails db:migrate, rails db:seed?

Current status =
I looked at the community question (rails) but can’t find it.
The other day, Mr. RUBYS taught me and received the following answer.

May I ask you one last question?
You normally generate users and products with rails db:seed , right?

The app also had a seed file that generated users and products by default.

But when I look at what I have deployed, neither users nor products are generated.

try:

fly ssh console -C “/app/bin/rails db:seed”

As a result, I was able to achieve what I wanted to do, but is there a specific command that corresponds to rails db:migrate:reset and rails db:migrate related to the database?

What I have tried =
I googled. I read the community question. I’ve read through the documentation. But it didn’t turn out.

my development environment =
M1 mac, rails, ruby, once successfully deployed with fly.io. I am using it for free. I have two apps deployed.

ruby ‘2.7.7’
rails ‘~> 5.1.6’

Could you please lend me your wisdom?
Thank you very much.

What I have tried =
I googled it.
Apparently I. It seems that the knowledge of postgres and database is not enough. I’ve also read the postgress docs on fly.io, could you give me some direction hints?

Also, for a similar case, I looked at heroku’s case.

heroku run rails db:reset

// abbreviation
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your ‘production’ database.
If you are sure you want to continue, run the same command with the environment variable:

It seems that it is intentionally played so as not to reset the production environment by mistake, but it is a problem when testing.

Method
Type the command below.

heroku pg:reset -a <app name>

For confirmation, you will be asked to re-enter the application name, so if you enter it, the DB will be reset.

After that, store the migration and the initial value.

heroku run rails db:migrate
heroku run rails db:seed

↑ End

I don’t think it will work this way, but could you give me a hint?

The application I have deployed is for personal use and I don’t really care if the database is reset.

There is nothing worth rails db:migrate:reset, and when I want to start over, do I have to redeploy in a different form?

You can make your own. Any file matching lib/tasks/*.rake can define new rake tasks. You can modify lib/tasks/fly.rake or create your own file.

For example, if you add the following to `lib/tasks/fly.rake’:

  task :reset => ['db:mgirate:reset', 'db:migrate', 'db:seed']

… you will be able to invoke it via:

bin/rails fly:reset
1 Like

thank you
I tried it but got the following error.

shinichikikukawa@shinichinoMacBook-Pro Attendance_System_A % bin/rails fly:reset
rails aborted!
Don’t know how to build task ‘db:mgirate:reset’ (See the list of available tasks with rails --tasks)
Did you mean? db:migrate:reset
/Users/shinichikikukawa/workspace/Attendance_System_A/bin/rails:9:in require' /Users/shinichikikukawa/workspace/Attendance_System_A/bin/rails:9:in <top (required)>’
/Users/shinichikikukawa/workspace/Attendance_System_A/bin/spring:15:in <top (required)>' bin/rails:3:in load’
bin/rails:3:in `’
Tasks: TOP => fly:reset
(See full trace by running task with --trace)
shinichikikukawa@shinichinoMacBook-Pro Attendance_System_A %
このソーステキストの詳細翻訳についての詳細を確認するにはソーステキストが必要です
フィードバックを送信
サイドパネル

Sorry, there is a typo in that. I meant db:migrate:reset.

1 Like

I thought so too.
Thank you for noticing.

And it looks like we did!
shinichikikukawa@shinichinoMacBook-Pro Attendance_System_A % bin/rails fly:reset
/Users/shinichikikukawa/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb:30: warning: rb_check_safe_obj will be removed in Ruby 3.0
Dropped database ‘db/development.sqlite3’
Dropped database ‘db/test.sqlite3’
/Users/shinichikikukawa/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb:30: warning: rb_check_safe_obj will be removed in Ruby 3.0
Created database ‘db/development.sqlite3’
/Users/shinichikikukawa/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb:30: warning: rb_check_safe_obj will be removed in Ruby 3.0
Created database ‘db/test.sqlite3’
/Users/shinichikikukawa/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb:30: warning: rb_check_safe_obj will be removed in Ruby 3.0
== 20220703132941 CreateUsers: migrating =====================================
– create_table(:users)
→ 0.0004s
== 20220703132941 CreateUsers: migrated (0.0005s) =============================

== 20220705212359 AddIndexToUsersEmail: migrating ============================
– add_index(:users, :email, {:unique=>true})
→ 0.0003s
== 20220705212359 AddIndexToUsersEmail: migrated (0.0004s) ====================

== 20220705221226 AddPasswordDigestToUsers: migrating =========================
– add_column(:users, :password_digest, :string)
→ 0.0004s
== 20220705221226 AddPasswordDigestToUsers: migrated (0.0004s) ================

== 20220715123443 AddRememberDigestToUsers: migrating =========================
– add_column(:users, :remember_digest, :string)
→ 0.0005s
== 20220715123443 AddRememberDigestToUsers: migrated (0.0005s) ================

== 20220720065015 AddAdminToUsers: migrating =================================
– add_column(:users, :admin, :boolean, {:default=>false})
→ 0.0004s
== 20220720065015 AddAdminToUsers: migrated (0.0004s) =========================

== 20220722114522 AddDepartmentToUsers: migrating ============================
– add_column(:users, :department, :string, {:default=>“Information System Department”})
→ 0.0004s
== 20220722114522 AddDepartmentToUsers: migrated (0.0004s) ====================

== 20220723133704 AddBasicInfoToUsers: migrating =============================
– add_column(:users, :basic_time, :datetime, {:default=>Thu, 05 Jan 2023 08:00:00 JST +09:00})
→ 0.0010s
– add_column(:users, :work_time, :datetime, {:default=>Thu, 05 Jan 2023 07:30:00 JST +09:00})
→ 0.0003s
== 20220723133704 AddBasicInfoToUsers: migrated (0.0043s) =====================

== 20220726134046 CreateAttendances: migrating ===============================
– create_table(:attendances)
→ 0.0007s
== 20220726134046 CreateAttendances: migrated (0.0007s) =======================

== 20221028124941 CreateBases: migrating =====================================
– create_table(:bases)
→ 0.0004s
== 20221028124941 CreateBases: migrated (0.0004s) =============================

== 20221117151428 AddEmployeeNumberToUsers: migrating =========================
– add_column(:users, :employee_number, :integer)
→ 0.0004s
== 20221117151428 AddEmployeeNumberToUsers: migrated (0.0004s) ================

== 20221123165343 RenameDepartmentColumnToUsers: migrating ====================
– rename_column(:users, :department, :affiliation)
→ 0.0041s
== 20221123165343 RenameDepartmentColumnToUsers: migrated (0.0042s) ===========

== 20221124131321 RenameBasicTimeColumnToUsers: migrating =====================
– rename_column(:users, :basic_time, :basic_work_time)
→ 0.0026s
== 20221124131321 RenameBasicTimeColumnToUsers: migrated (0.0026s) ============

== 20221124133215 AddUidToUsers: migrating ===================================
– add_column(:users, :uid, :integer)
→ 0.0004s
== 20221124133215 AddUidToUsers: migrated (0.0005s) ===========================

== 20221124133514 AddDesignatedWorkStartTimeToUsers: migrating ================
– add_column(:users, :designated_work_start_time, :datetime, {:default=>“2023-1-1 00:00:00”})
→ 0.0004s
== 20221124133514 AddDesignatedWorkStartTimeToUsers: migrated (0.0004s) =======

== 20221124133547 AddDesignatedWorkEndTimeToUsers: migrating ==================
– add_column(:users, :designated_work_end_time, :datetime, {:default=>“2023-1-1 9:00:00”})
→ 0.0004s
== 20221124133547 AddDesignatedWorkEndTimeToUsers: migrated (0.0004s) =========

== 20221124133716 AddSuperiorToUsers: migrating ==============================
– add_column(:users, :superior, :boolean, {:default=>false})
→ 0.0004s
== 20221124133716 AddSuperiorToUsers: migrated (0.0005s) ======================

== 20230103152511 AddOvertimeRequestToAttendances: migrating ==================
– add_column(:at

Thank you!
I will recommend this to my acquaintance of Japanese engineers!
fly.io, the fastest and coolest alternative to heroku.
If anything else comes up, I’ll look into it myself, but please let me know.
Thank you very much.

thank you for your hard work.
I thought the previous issue was resolved,
I got an error as below.

--> This release will not be available until the release command succeeds.
         Starting instance
         Configuring virtual machine
         Pulling container image
         Unpacking image
         Starting instance
         Configuring virtual machine
         Pulling container image
         Unpacking image
Error release command failed, deployment aborted


shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % fly deploy
==> Verifying app config
--> Verified app config
==> Building image
Remote builder fly-builder-twilight-glitter-5810 ready
==> Creating build context
--> Creating build context done
==> Building image with Docker
--> docker host: 20.10.12 linux x86_64
Sending build context to Docker daemon  46.72kB
[+] Building 15.1s (21/21) FINISHED                                                                                 
 => [internal] load remote build context                                                                       0.0s
 => copy /context /                                                                                            0.1s
 => resolve image config for docker.io/docker/dockerfile:experimental                                          1.5s
 => CACHED docker-image://docker.io/docker/dockerfile:experimental@sha256:600e5c62eedff338b3f7a0850beb7c05866  0.0s
 => [internal] load metadata for quay.io/evl.ms/fullstaq-ruby:2.7.7-jemalloc-slim                              0.8s
 => [base 1/5] FROM quay.io/evl.ms/fullstaq-ruby:2.7.7-jemalloc-slim@sha256:48602aaf0da644809dee265b8ebca2a7e  0.0s
 => CACHED [base 2/5] RUN mkdir /app                                                                           0.0s
 => CACHED [base 3/5] WORKDIR /app                                                                             0.0s
 => CACHED [base 4/5] RUN mkdir -p tmp/pids                                                                    0.0s
 => CACHED [base 5/5] RUN gem update --system --no-document &&     gem install -N bundler -v 2.1.4             0.0s
 => CACHED [stage-3 1/7] RUN --mount=type=cache,id=prod-apt-cache,sharing=locked,target=/var/cache/apt     --  0.0s
 => CACHED [build_deps 1/1] RUN --mount=type=cache,id=dev-apt-cache,sharing=locked,target=/var/cache/apt       0.0s
 => CACHED [gems 1/2] COPY Gemfile* ./                                                                         0.0s
 => CACHED [gems 2/2] RUN bundle install && rm -rf vendor/bundle/ruby/*/cache                                  0.0s
 => CACHED [stage-3 2/7] COPY --from=gems /app /app                                                            0.0s
 => CACHED [stage-3 3/7] COPY --from=gems /usr/lib/fullstaq-ruby/versions /usr/lib/fullstaq-ruby/versions      0.0s
 => CACHED [stage-3 4/7] COPY --from=gems /usr/local/bundle /usr/local/bundle                                  0.0s
 => [stage-3 5/7] COPY . .                                                                                     0.0s
 => [stage-3 6/7] RUN chmod +x /app/bin/* &&     sed -i 's/ruby.exe\r*/ruby/' /app/bin/* &&     sed -i 's/rub  0.2s
 => [stage-3 7/7] RUN bin/rails fly:build                                                                     12.2s
 => exporting to image                                                                                         0.1s
 => => exporting layers                                                                                        0.1s
 => => writing image sha256:ff3bd663234df107b9262a442cf3a55aa5517acf76ec049a87aa1d792ecac300                   0.0s
 => => naming to registry.fly.io/attendance-system--a:deployment-01GNZ60Q0WWPB6SDR6JY85KS8M                    0.0s
--> Building image done
==> Pushing image to fly
The push refers to repository [registry.fly.io/attendance-system--a]
e5c03050283b: Pushed 
fa1d52ca3adc: Pushed 
6c43ad8fe5f1: Pushed 
ffbfe87b76e1: Layer already exists 
bbeb409800d3: Layer already exists 
da6fc6577ec7: Layer already exists 
be64ae804d17: Layer already exists 
1ef3d0596caf: Layer already exists 
b24b58f43e32: Layer already exists 
5f70bf18a086: Layer already exists 
b04a69a25b61: Layer already exists 
ffc266862628: Layer already exists 
7b6f75f8765b: Layer already exists 
deployment-01GNZ60Q0WWPB6SDR6JY85KS8M: digest: sha256:16bf94264dbe7c9c63e44848273a30e70992ce56d073684b0fff7a906c91b177 size: 3046
--> Pushing image done
image: registry.fly.io/attendance-system--a:deployment-01GNZ60Q0WWPB6SDR6JY85KS8M
image size: 335 MB
==> Creating release
--> release v2 created

--> You can detach the terminal anytime without stopping the deployment
==> Release command detected: bin/rails fly:release

--> This release will not be available until the release command succeeds.
         Starting instance
         Configuring virtual machine
         Pulling container image
         Unpacking image
         Preparing kernel init
         Configuring firecracker
         Starting init (commit: f447594)...
         no label, UUID=883b63b0-a1b8-4d63-a81a-3080391ffc7f
         Preparing to run: `bin/rails fly:release` as root
         2023/01/04 20:02:46 listening on [fdaa:1:1294:a7b:9b:d9be:a31c:2]:22 (DNS: [fdaa::3]:53)
         D, [2023-01-04T20:02:49.635620 #523] DEBUG -- :   ActiveRecord::InternalMetadata Load (1.3ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
         D, [2023-01-04T20:02:49.643324 #523] DEBUG -- :    (1.0ms)  COMMIT
         D, [2023-01-04T20:02:49.644620 #523] DEBUG -- :    (1.2ms)  SELECT pg_advisory_unlock(3183507114762788625)
         Starting clean up.
         Starting instance
         Configuring virtual machine
         Pulling container image
         Unpacking image
         Preparing kernel init
         Configuring firecracker
         Starting virtual machine
         Starting init (commit: f447594)...
         Setting up swapspace version 1, size = 512 MiB (536866816 bytes)
         no label, UUID=883b63b0-a1b8-4d63-a81a-3080391ffc7f
         Preparing to run: `bin/rails fly:release` as root
         2023/01/04 20:02:46 listening on [fdaa:1:1294:a7b:9b:d9be:a31c:2]:22 (DNS: [fdaa::3]:53)
         W, [2023-01-04T20:02:48.430036 #523]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.previous_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:8:in `<top (required)>')
         W, [2023-01-04T20:02:48.430120 #523]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.next_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:9:in `<top (required)>')
         D, [2023-01-04T20:02:49.608922 #523] DEBUG -- :    (1.1ms)  SELECT pg_try_advisory_lock(3183507114762788625)
         D, [2023-01-04T20:02:49.623671 #523] DEBUG -- :    (1.8ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
         D, [2023-01-04T20:02:49.635620 #523] DEBUG -- :   ActiveRecord::InternalMetadata Load (1.3ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
         D, [2023-01-04T20:02:49.641533 #523] DEBUG -- :    (1.0ms)  BEGIN
         D, [2023-01-04T20:02:49.643324 #523] DEBUG -- :    (1.0ms)  COMMIT
         D, [2023-01-04T20:02:49.644620 #523] DEBUG -- :    (1.2ms)  SELECT pg_advisory_unlock(3183507114762788625)
         Starting clean up.
         Starting instance
         Configuring virtual machine
         Pulling container image
         Unpacking image
         Preparing kernel init
         Configuring firecracker
         Starting virtual machine
         Starting init (commit: f447594)...
         Setting up swapspace version 1, size = 512 MiB (536866816 bytes)
         no label, UUID=883b63b0-a1b8-4d63-a81a-3080391ffc7f
         Preparing to run: `bin/rails fly:release` as root
         2023/01/04 20:02:46 listening on [fdaa:1:1294:a7b:9b:d9be:a31c:2]:22 (DNS: [fdaa::3]:53)
         W, [2023-01-04T20:02:48.430036 #523]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.previous_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:8:in `<top (required)>')
         W, [2023-01-04T20:02:48.430120 #523]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.next_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:9:in `<top (required)>')
         D, [2023-01-04T20:02:49.608922 #523] DEBUG -- :    (1.1ms)  SELECT pg_try_advisory_lock(3183507114762788625)
         D, [2023-01-04T20:02:49.623671 #523] DEBUG -- :    (1.8ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
         D, [2023-01-04T20:02:49.635620 #523] DEBUG -- :   ActiveRecord::InternalMetadata Load (1.3ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
         D, [2023-01-04T20:02:49.641533 #523] DEBUG -- :    (1.0ms)  BEGIN
         D, [2023-01-04T20:02:49.643324 #523] DEBUG -- :    (1.0ms)  COMMIT
         D, [2023-01-04T20:02:49.644620 #523] DEBUG -- :    (1.2ms)  SELECT pg_advisory_unlock(3183507114762788625)
         Starting clean up.
==> Monitoring deployment
Logs: https://fly.io/apps/attendance-system--a/monitoring

 1 desired, 1 placed, 1 healthy, 0 unhealthy [health checks: 1 total, 1 passing]
--> v2 deployed successfully

shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % fly ssh console -C "/app/bin/rails db:seed"
Connecting to fdaa:1:1294:a7b:9b:582c:e4bd:2... complete
W, [2023-01-04T20:04:43.657713 #542]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.previous_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:8:in `<top (required)>')
W, [2023-01-04T20:04:43.659425 #542]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.next_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:9:in `<top (required)>')
D, [2023-01-04T20:04:43.834773 #542] DEBUG -- :    (1.4ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2023-01-04T20:04:44.071222 #542] DEBUG -- :    (1.4ms)  BEGIN
D, [2023-01-04T20:04:44.075180 #542] DEBUG -- :   User Exists (1.6ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "sample@email.com"], ["LIMIT", 1]]
D, [2023-01-04T20:04:45.408425 #542] DEBUG -- :    (1.4ms)  ROLLBACK
rails aborted!
ActiveRecord::RecordInvalid: バリデーションに失敗しました: メールアドレスはすでに存在します
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/validations.rb:78:in `raise_validation_error'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/validations.rb:50:in `save!'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/attribute_methods/dirty.rb:43:in `save!'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/transactions.rb:313:in `block in save!'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/transactions.rb:384:in `block in with_transaction_returning_status'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `block in transaction'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb:194:in `block in within_new_transaction'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb:191:in `synchronize'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb:191:in `within_new_transaction'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `transaction'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/transactions.rb:210:in `transaction'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/transactions.rb:381:in `with_transaction_returning_status'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/transactions.rb:313:in `save!'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/suppressor.rb:46:in `save!'
/app/vendor/bu%                                                                                                     
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % task :reset => ['db:mgirate:reset', 'db:migrate', 'db:seed']
zsh: bad pattern: [db:mgirate:reset,
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % task :reset => ['db:mgirate:reset', 'db:migrate', 'db:seed']
zsh: bad pattern: [db:mgirate:reset,
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % 

fly.rake

# commands used to deploy a Rails application
namespace :fly do
  # BUILD step:
  #  - changes to the filesystem made here DO get deployed
  #  - NO access to secrets, volumes, databases
  #  - Failures here prevent deployment
  task :build => 'assets:precompile'

  # RELEASE step:
  #  - changes to the filesystem made here are DISCARDED
  #  - full access to secrets, databases
  #  - failures here prevent deployment
  task :release => 'db:migrate'
  task :reset => ['db:migrate:reset', 'db:migrate', 'db:seed']
  # SERVER step:
  #  - changes to the filesystem made here are deployed
  #  - full access to secrets, databases
  #  - failures here result in VM being stated, shutdown, and rolled back
  #    to last successful deploy (if any).
  task :server => :swapfile do
    sh 'bin/rails server'
  end

  # optional SWAPFILE task:
  #  - adjust fallocate size as needed
  #  - performance critical applications should scale memory to the
  #    point where swap is rarely used.  'fly scale help' for details.
  #  - disable by removing dependency on the :server task, thus:
  #        task :server do
  task :swapfile do
    sh 'fallocate -l 512M /swapfile'
    sh 'chmod 0600 /swapfile'
    sh 'mkswap /swapfile'
    sh 'echo 10 > /proc/sys/vm/swappiness'
    sh 'swapon /swapfile'
  end
end

I was told before
fly ssh console -C "/app/bin/rails db:seed”

I tried to modify the rake file instead of and see if it could be deployed.
However, at the end of the day, I got an error and tried again.

fly ssh console -C "/app/bin/rails db:seed”
# commands used to deploy a Rails application
namespace :fly do
  # BUILD step:
  #  - changes to the filesystem made here DO get deployed
  #  - NO access to secrets, volumes, databases
  #  - Failures here prevent deployment
  task :build => 'assets:precompile'

  # RELEASE step:
  #  - changes to the filesystem made here are DISCARDED
  #  - full access to secrets, databases
  #  - failures here prevent deployment
  task :release => ['db:migrate', 'db:seed']
  task :reset => ['db:migrate:reset', 'db:migrate', 'db:seed']
  # SERVER step:
  #  - changes to the filesystem made here are deployed
  #  - full access to secrets, databases
  #  - failures here result in VM being stated, shutdown, and rolled back
  #    to last successful deploy (if any).
  task :server => :swapfile do
    sh 'bin/rails server'
  end

  # optional SWAPFILE task:
  #  - adjust fallocate size as needed
  #  - performance critical applications should scale memory to the
  #    point where swap is rarely used.  'fly scale help' for details.
  #  - disable by removing dependency on the :server task, thus:
  #        task :server do
  task :swapfile do
    sh 'fallocate -l 512M /swapfile'
    sh 'chmod 0600 /swapfile'
    sh 'mkswap /swapfile'
    sh 'echo 10 > /proc/sys/vm/swappiness'
    sh 'swapon /swapfile'
  end
end

To me it looks like your database already exists, migrations have been run, and the seed data has already been loaded.

Perhaps what you are looking for instead is:

fly ssh console -C "/app/bin/rails fly:reset"
1 Like

thank you.
I have just returned.
I got an error.

shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % task :reset => ['db:mgirate:reset', 'db:migrate', 'db:seed']
zsh: bad pattern: [db:mgirate:reset,
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % task :reset => ['db:mgirate:reset', 'db:migrate', 'db:seed']
zsh: bad pattern: [db:mgirate:reset,
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % fly ssh console -C "/app/bin/rails fly:reset"
Connecting to fdaa:1:1294:a7b:9b:582c:e4bd:2... complete
W, [2023-01-05T11:06:38.757067 #543]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.previous_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:8:in `<top (required)>')
W, [2023-01-05T11:06:38.759320 #543]  WARN -- : DEPRECATION WARNING: set the 'will_paginate.next_label' key in your i18n locale instead of editing pagination_options (called from /app/config/environment.rb:9:in `<top (required)>')
D, [2023-01-05T11:06:38.814148 #543] DEBUG -- :    (1.4ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2023-01-05T11:06:38.822953 #543] DEBUG -- :    (1.2ms)  SELECT "ar_internal_metadata"."value" FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1  [["key", "environment"]]
D, [2023-01-05T11:06:38.826552 #543] DEBUG -- :    (1.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2023-01-05T11:06:38.829489 #543] DEBUG -- :    (1.1ms)  SELECT "ar_internal_metadata"."value" FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1  [["key", "environment"]]
D, [2023-01-05T11:06:38.832186 #543] DEBUG -- :    (1.1ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
D, [2023-01-05T11:06:38.834916 #543] DEBUG -- :    (1.0ms)  SELECT "ar_internal_metadata"."value" FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1  [["key", "environment"]]
rails aborted!
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your 'production' database.
If you are sure you want to continue, run the same command with the environment variable:
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/tasks/database_tasks.rb:59:in `check_protected_environments!'
/app/vendor/bundle/ruby/2.7.0/gems/activerecord-5.1.7/lib/active_record/railties/databases.rake:11:in `block (2 levels) in <top (required)>'
/app/vendor/bundle/ruby/2.7.0/gems/railties-5.1.7/lib/rails/commands/rake/rake_command.rb:21:in `block in perform'
/app/vendor/bundle/ruby/2.7.0/gems/railties-5.1.7/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/app/vendor/bundle/ruby/2.7.0/gems/railties-5.1.7/lib/rails/command.rb:46:in `invoke'
/app/vendor/bundle/ruby/2.7.0/gems/railties-5.1.7/lib/rails/commands.rb:16:in `<top (required)>'
/app/bin/rails:10:in `require'
/app/bin/rails:10:in `<main>'
Tasks: TOP => fly:reset => db:migrate:reset => db:drop => db:check_protected_environments
(See full trace by running task with --trace)
shinichikikukawa@ShinichinoMacBook-Pro Attendance_System_A % 

# syntax = docker/dockerfile:experimental

# Dockerfile used to build a deployable image for a Rails application.
# Adjust as required.
#
# Common adjustments you may need to make over time:
#  * Modify version numbers for Ruby, Bundler, and other products.
#  * Add library packages needed at build time for your gems, node modules.
#  * Add deployment packages needed by your application
#  * Add (often fake) secrets needed to compile your assets

#######################################################################

# Learn more about the chosen Ruby stack, Fullstaq Ruby, here:
#   https://github.com/evilmartians/fullstaq-ruby-docker.
#
# We recommend using the highest patch level for better security and
# performance.

ARG RUBY_VERSION=2.7.7
ARG VARIANT=jemalloc-slim
FROM quay.io/evl.ms/fullstaq-ruby:${RUBY_VERSION}-${VARIANT} as base

LABEL fly_launch_runtime="rails"

ARG BUNDLER_VERSION=2.1.4

ARG RAILS_ENV=production
ENV RAILS_ENV=${RAILS_ENV}

ENV RAILS_SERVE_STATIC_FILES true
ENV RAILS_LOG_TO_STDOUT true

ARG BUNDLE_WITHOUT=development:test
ARG BUNDLE_PATH=vendor/bundle
ENV BUNDLE_PATH ${BUNDLE_PATH}
ENV BUNDLE_WITHOUT ${BUNDLE_WITHOUT}

RUN mkdir /app
WORKDIR /app
RUN mkdir -p tmp/pids

RUN gem update --system --no-document && \
    gem install -N bundler -v ${BUNDLER_VERSION}

#######################################################################

# install packages only needed at build time

FROM base as build_deps

ARG BUILD_PACKAGES="git build-essential libpq-dev wget vim curl gzip xz-utils libsqlite3-dev"
ENV BUILD_PACKAGES ${BUILD_PACKAGES}

RUN --mount=type=cache,id=dev-apt-cache,sharing=locked,target=/var/cache/apt \
    --mount=type=cache,id=dev-apt-lib,sharing=locked,target=/var/lib/apt \
    apt-get update -qq && \
    apt-get install --no-install-recommends -y ${BUILD_PACKAGES} \
    && rm -rf /var/lib/apt/lists /var/cache/apt/archives

#######################################################################

# install gems

FROM build_deps as gems

COPY Gemfile* ./
RUN bundle install && rm -rf vendor/bundle/ruby/*/cache

#######################################################################

# install deployment packages

FROM base
ARG DEPLOY_PACKAGES="postgresql-client file vim curl gzip libsqlite3-0 nodejs"
ENV DEPLOY_PACKAGES=${DEPLOY_PACKAGES}

RUN --mount=type=cache,id=prod-apt-cache,sharing=locked,target=/var/cache/apt \
    --mount=type=cache,id=prod-apt-lib,sharing=locked,target=/var/lib/apt \
    apt-get update -qq && \
    apt-get install --no-install-recommends -y \
    ${DEPLOY_PACKAGES} \
    && rm -rf /var/lib/apt/lists /var/cache/apt/archives

# copy installed gems
COPY --from=gems /app /app
COPY --from=gems /usr/lib/fullstaq-ruby/versions /usr/lib/fullstaq-ruby/versions
COPY --from=gems /usr/local/bundle /usr/local/bundle

#######################################################################

# Deploy your application
COPY . .

# Adjust binstubs to run on Linux and set current working directory
RUN chmod +x /app/bin/* && \
    sed -i 's/ruby.exe\r*/ruby/' /app/bin/* && \
    sed -i 's/ruby\r*/ruby/' /app/bin/* && \
    sed -i '/^#!/aDir.chdir File.expand_path("..", __dir__)' /app/bin/*

# The following enable assets to precompile on the build server.  Adjust
# as necessary.  If no combination works for you, see:
# https://fly.io/docs/rails/getting-started/existing/#access-to-environment-variables-at-build-time
ENV SECRET_KEY_BASE 1
# ENV AWS_ACCESS_KEY_ID=1
# ENV AWS_SECRET_ACCESS_KEY=1

# Run build task defined in lib/tasks/fly.rake
ARG BUILD_COMMAND="bin/rails fly:build"
RUN ${BUILD_COMMAND}

# Default server start instructions.  Generally Overridden by fly.toml.
ENV PORT 8080
ARG SERVER_COMMAND="bin/rails fly:server"
ENV SERVER_COMMAND ${SERVER_COMMAND}
CMD ${SERVER_COMMAND}

I found the following article and hypothesized that it might be similar to this.


Rails5 production cannot rake db: drop, normally

overview
From Rails5, in production mode, a function has been added to prevent the execution of commands that destroy the DB, such as db:drop.
Below is the procedure for rake db:drop on production.

Set environment of ar_internal_metadata table to production
First of all, how to deal with errors that occur when you dump a DB in a different environment such as development or staging and put it in the production DB.
If you only want to know how to rake db:drop in production, go to the next section.

If it is not in production, you will get an error like this

$ RAILS_ENV=production bundle exec rake db: drop
rake aborted!
ActiveRecord::EnvironmentMismatchError: You are attempting to modify a database that was last run in staging environment.
If you are sure you want to continue, first set the environment using:

     bin/rails db:environment:set RAILS_ENV=production

cause
This error occurs when the environment set in the ar_internal_metadata table does not match the one specified in the command you are trying to execute.
This happens when you dump a DB in a different environment such as development or staging and put it in the production DB.

mysql> select * from ar_internal_metadata;
±------------±------------±-------------------- ±--------------------+
| key | value | created_at | updated_at |
±------------±------------±-------------------- ±--------------------+
development | 2017-03-28 05:54:51 | 2017-03-28 05:54:51 |
±------------±------------±-------------------- ±--------------------+
1 row in set (0.00 sec)
approach
Update the environment of ar_internal_metadata to production with the command below.

$ bundle exec rails db:environment:set RAILS_ENV=production
An error occurs when executing db destruction processing in production
I get an error like this

$ RAILS_ENV=production bundle exec rake db: drop
rake aborted!
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your ‘production’ database.
If you are sure you want to continue, run the same command with the environment variable:
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
cause
reference
If you want to intentionally destroy the DB in the production environment, as shown in the error message,
It is OK if you specify the environment variable DISABLE_DATABASE_ENVIRONMENT_CHECK=1.
The tasks targeted for prevention processing are as follows.

db: drop
db:drop:all
db:purge
db:purge:all
db:purge:test
db:schema:load

About prevention processing of DB destruction type task that entered Rails 5

Rails5 seems to have added a function to prevent commands that destroy the DB.

approach
As per the reference article, in the environment variable
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
can be added, so you can drop it with the following command.

$ RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bundle exec rake db:drop

that’s all

You can put that in your rakefile:

  task :disable_database_environment_check do
    ENV['DISABLE_DATABASE_ENVIRONMENT_CHECK'] = '1'
  end

  task :reset => [
    'fly:disable_database_environment_check',
    'db:migrate:reset',
    'db:migrate',
    'db:seed'
  ]
1 Like

I tried.
and
got an error. I will send you a separate photo.

The following commands in the previous article have not been typed.

$ bundle exec rails db:environment:set RAILS_ENV=production

$ RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bundle exec rake db:drop

Hello!
Since then, I’ve researched and tried many things, but the problem persists.

I’ll sort things out for now.
What I want to achieve =
I don’t have another user right now, so I want to reset the db once.
I want the command corresponding to rails:db:migrate:reset to work.

Current situation =
Let me know and I did the following:

the environment variable
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
can be added

You can put that in your rakefile:

task :disable_database_environment_check do
ENV[‘DISABLE_DATABASE_ENVIRONMENT_CHECK’] = ‘1’
end

task :reset => [
‘fly:disable_database_environment_check’,
‘db:migrate:reset’,
‘db:migrate’,
‘db:seed’
]

result =
I got an error. (As screenshots from the previous thread)

What I tried after that =
Deploy another application, and also with the environment settings you taught me,

fly ssh console -C “/app/bin/rails fly:reset”

but it didn’t work. I got an error.
(Another error has occurred. I will attach a separate screenshot.)

What I have tried on it =
It said that the user had access and couldn’t, so I logged out and cleared the chrome session.
Still not good.

Could you give me some hints?

fly.rake

# commands used to deploy a Rails application
namespace :fly do
  # BUILD step:
  #  - changes to the filesystem made here DO get deployed
  #  - NO access to secrets, volumes, databases
  #  - Failures here prevent deployment
  task :build => 'assets:precompile'

  # RELEASE step:
  #  - changes to the filesystem made here are DISCARDED
  #  - full access to secrets, databases
  #  - failures here prevent deployment
  task :release => 'db:migrate'
  
  task :disable_database_environment_check do
    ENV['DISABLE_DATABASE_ENVIRONMENT_CHECK'] = '1'
  end

  task :reset => [
    'fly:disable_database_environment_check',
    'db:migrate:reset',
    'db:migrate',
    'db:seed'
  ]
  # SERVER step:
  #  - changes to the filesystem made here are deployed
  #  - full access to secrets, databases
  #  - failures here result in VM being stated, shutdown, and rolled back
  #    to last successful deploy (if any).
  task :server => :swapfile do
    sh 'bin/rails server'
  end

  # optional SWAPFILE task:
  #  - adjust fallocate size as needed
  #  - performance critical applications should scale memory to the
  #    point where swap is rarely used.  'fly scale help' for details.
  #  - disable by removing dependency on the :server task, thus:
  #        task :server do
  task :swapfile do
    sh 'fallocate -l 512M /swapfile'
    sh 'chmod 0600 /swapfile'
    sh 'mkswap /swapfile'
    sh 'echo 10 > /proc/sys/vm/swappiness'
    sh 'swapon /swapfile'
  end
end

I used the following article as a reference.

About prevention processing of DB destruction type task that entered Rails 5
small story.

From Rails 5, there is a mechanism to prevent the execution of DB destruction tasks in the production environment.

For example, when I try to run db:drop in my production environment, I get the following error (ActiveRecord::ProtectedEnvironmentError).

$ RAILS_ENV=production ./bin/rails db:drop
rails aborted!
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your ‘production’ database
If you are sure you want to continue, run the same command with the environment variable
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
As you can see, this is a mechanism to prevent accidentally destroying the DB in the production environment (By the way, according to the PR comment, I actually accidentally destroyed the DB on Heroku and would like to ask for recovery. It seems that the request was allotted).

If you want to intentionally destroy the DB in the production environment, just specify the environment variable DISABLE_DATABASE_ENVIRONMENT_CHECK=1 as shown in the error message.

The tasks targeted for prevention processing are as follows.

db: drop
db:drop:all
db:purge
db:purge:all
db:purge:test
db:schema:load
By default only the production environment is blocked, but this can be changed. If you want to specify an environment other than production, you can specify the environment to be protected in ActiveRecord::Base.protected_environments.

#config/application.rb
ActiveRecord::Base.protected_environments = %w(production staging)
$ RAILS_ENV=staging ./bin/rails db:drop
rails aborted!
ActiveRecord::ProtectedEnvironmentError: You are attempting to run a destructive action against your ‘staging’ database
If you are sure you want to continue, run the same command with the environment variable
DISABLE_DATABASE_ENVIRONMENT_CHECK=1
You can specify an Array for ActiveRecord::Base.protected_environments, so of course it is possible to target multiple environments to be protected (the value will be overwritten, so if you want to specify the environment in addition to production, use production must be specified explicitly).

By the way, the check of environments is done by comparing with the environment where migration processing etc. were performed at the end.

What this means is that from Rails 5, when db:migrate or schema load processing is performed, the information of the environment that performed the processing is stored in the DB.

Specifically, a table named ar_internal_metadata (in the default case) is created inside Rails and environment information is stored there.

irb(main):001:0* ActiveRecord::InternalMetadata.all
ActiveRecord::InternalMetadata Load (0.2ms) SELECT “ar_internal_metadata”.* FROM “ar_internal_metadata”
=> #<:relation key: value: created_at: updated_at:>]>
</:relation>

  • If table_name_prefix / table_name_suffix is set, the value will be attached before and after the table name. Also, the table name can be changed with ActiveRecord::Base.internal_metadata_table_name. Furthermore, until Rails 5.0.0.beta2, the default table name was active_record_internal_metadatas.

The value stored in the ar_internal_metadata table is compared with the environment in which the process is to be executed, so of course the process cannot be performed without the ar_internal_metadata table.

Therefore, if you try to execute a destructive task such as db:drop in a state without ar_internal_metadata (when updating from Rails 4 to Rails 5 and db:migrate has never been executed), Environment information An error (ActiveRecord::NoEnvironmentInSchemaError) will occur.

$ ./bin/rails db:drop
rails aborted!
ActiveRecord::NoEnvironmentInSchemaError:

Environment data not found in the schema. To resolve this issue, run:

 bin/rails db:environment:set RAILS_ENV=development

This happens regardless of whether the environment is protected or not.

To resolve it, run db:environment:set task as shown in the error message (running db:migrate is also OK).

By the way, if for some reason the environment in the ar_internal_metadata table contains a different value than the environment you are trying to process, this will also result in an error (ActiveRecord::EnvironmentMismatchError).

For example, let’s say that the environment in the ar_internal_metadata table in the development environment contains the value test.

irb(main):001:0* Rails.env
=> “development”
irb(main):002:0> ActiveRecord::InternalMetadata.all
ActiveRecord::InternalMetadata Load (0.2ms) SELECT “ar_internal_metadata”.* FROM “ar_internal_metadata”
=> #<:relation key: value: created_at: updated_at:>]>
irb(main):003:0>
</:relation>
Executing a DB destruction task in this state will result in the following.

$ ./bin/rails db:drop
rails aborted!
ActiveRecord::EnvironmentMismatchError: You are attempting to modify a database that was last run in test environment.
You are running in development environment. If you are sure you want to continue, first set the environment using:

 bin/rails db:environment:set RAILS_ENV=development

In this case as well, it is OK if you execute db:environment:set task as shown in the error message.

If you use the same DB in different environments, I feel like it’s going to cause a lot of trouble.

Miscellaneous impressions
I think it’s a very good thing that the DB destruction task prevention process that was included in Rails 5 is now provided by default. This is a complete digression, but I made a gem to do something similar, but it is no longer needed. No, it’s a good thing.

And I feel that ActiveRecord::EnvironmentMismatchError will occur from time to time…

I used the following article as a reference.

I kept it as a draft as a memo for myself, so I will publish it.
(In short, the intention is to publish it as a memorandum and look back later when you are in trouble)

It may be common sense, but it was my first experience, so I will make a note of it.

In the Rails “Production environment” used as a test environment,
“rails db:drop” failed.

This is to avoid accidentally corrupting the DB in a production environment,
Prevention measures prepared by Rails.

So how do you do “rails db:drop”
The article below was helpful.

About prevention processing of DB destruction type task that entered Rails 5 | Daily miscellaneous notes

First set the environment variable

export DISABLE_DATABASE_ENVIRONMENT_CHECK=1
Set production to environment

bin/rails db:environment;set RAILS_ENV=production
Now you can drop

rails :db:drop