It is a complete muscle training set that also serves as a memorandum to get used to DB operation of Ruby on Rails.
I think the procedure for deleting a table is a little complicated for beginners including myself, so I hope it will be useful for repeated practice.
Since it is assumed that the database is already installed in the Rails application you are using, if you have not created the database yet, please prepare the database with "rails db: create".
Ruby 2.7.2 Rails 6.0.3
First, change from the terminal to the directory containing the Rails app.
>cd (folder address)
Create a migration file for model creation. (Example: model name "User", field name "name", "address", "age")
> rails g model User name:text address:text age:integer
At this point, a class file and a migration file that define the "User" model are created, but no tables are generated.
Migration is required to generate the table.
> rails db:migrate
This will create a "users" table based on the "User" model.
__ * The table name is different from the model name because of the rails naming convention __. Reference: "I tried to summarize the naming convention of Rails DB model" https://qiita.com/seri1234/items/8ca4b52d82390929195f
Launch the Rails console.
> rails console
Add a record to the new row.
irb(main):001:0> user = User.new irb(main):002:0> user.name = "John Smith" irb(main):003:0> user.save
Make sure the record has been added.
irb(main):004:0> users = User.all
After confirming, delete the created record. (The argument of find () is the record index)
After deleting the record, exit the Rails console and return to the terminal.
First, delete the file created when the model was created.
> rails destroy model User
This will remove the "User" model.
__ Please note that there is still a "users" table at this point. __
Next, create a migration file for deleting the table. ("Drop_table_users" can be any name)
> rails generate migration drop_table_users
A migration file called "~ drop_table_users.rb" with numbers at the beginning will be created under "app name / db / migrate /".
Open this file with a text editor, add a command to delete the table in "def change", and save it by overwriting.
class DropTableUsers < ActiveRecord::Migration[6.0] def change #Add one line below drop_table :users end end
Perform the migration.
> rails db:migrate
The table is deleted, and this completes the flow.