[RUBY] [Mein Memo] Lass uns mit Pry / DB mit Rails auskommen

Einführung

Beim Betrieb der Datenbank mit Pry with Rails Hinterlassen Sie die erforderlichen Befehle und Ideen als Ihre eigenen Notizen.

Umgebung

MacOS Mojave Ruby 2.6.4 Rails 6.0.3.3 Vue 2.6.12 Webpack 4.44.2 yarn 1.22.5 Docker 2.3.0.5 VScode

Umgebung

Die Vue Rails 6-Umgebungskonstruktion mit Docker ist unten zusammengefasst. Link: So verknüpfen Sie Rails6 Vue (aus der Umgebungskonstruktion)

Modell- und DB-Migration

Ich werde den Docker-Container anheben.

python


Docker-compose up

Erstellen eines Artikelmodells

python


Docker-compose exec web rails g model Article name:string content:text

Running via Spring preloader in process 207
      invoke  active_record
      create    db/migrate/20200926174356_create_articles.rb
      create    app/models/article.rb
      invoke    test_unit
      create      test/models/article_test.rb
      create      test/fixtures/articles.yml

Kommentar Modell erstellen

python


Docker-compose exec web rails g model Comment comment:text

Running via Spring preloader in process 276
      invoke  active_record
      create    db/migrate/20200926174846_create_comments.rb
      create    app/models/comment.rb
      invoke    test_unit
      create      test/models/comment_test.rb
      create      test/fixtures/comments.yml

Reflexion in DB

python


Docker-compose exec web rails db:migrate

== 20200926174356 CreateArticles: migrating ===================================
-- create_table(:articles)
   -> 0.0505s
== 20200926174356 CreateArticles: migrated (0.0519s) ==========================

== 20200926174846 CreateComments: migrating ===================================
-- create_table(:comments)
   -> 0.0296s
== 20200926174846 CreateComments: migrated (0.0310s) ==========================

DB-Statusprüfung

python


Docker-compose exec web rails db:migrate:status

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20200926174356  Create articles
   up     20200926174846  Create comments

DB-Version

python


Docker_Rails6_Vue hiroki$ Docker-compose exec web rails db:version
Current version: 20200926174846

Überprüfen Sie die Version auf Schema.rb

schema.rb


ActiveRecord::Schema.define(version: 2020_09_26_174846) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "articles", force: :cascade do |t|
    t.string "name"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "comments", force: :cascade do |t|
    t.text "comment"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

DB-Rollback

Wenn Docker-compose exec Web Rails db: rollback STEP = 2 ist, ist es [+1] down.

Mit anderen Worten Docker-compose exec web rails db:rollback STEP=1 Wann Docker-compose exec web rails db:rollback Ist dasselbe

python


Docker-compose exec web rails db:rollback

== 20200926174846 CreateComments: reverting ===================================
-- drop_table(:comments)
   -> 0.0104s
== 20200926174846 CreateComments: reverted (0.0156s) ==========================

DB-Statusprüfung

Es ist erforderlich, die Migrationsdatei zu löschen und DB-Spalten zum Zeitpunkt des Ausfalls hinzuzufügen. Im Allgemeinen wird eine Migrationsdatei zum Hinzufügen einer DB-Spalte erstellt und beschrieben.

python


Docker-compose exec web rails db:migrate:status

database: myapp_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20200926174356  Create articles
  down    20200926174846  Create comments

Docker-Compose Exec Web Rails Datenbank: Migrieren und zurücksetzen.

Starten Sie Pry

Starten Sie Pry

python


Docker-compose exec web rails c

Running via Spring preloader in process 1191
Loading development environment (Rails 6.0.3.3)
[1] pry(main)> 

Erstellen Sie ein neues Artikelobjekt

python


pry(main)> @article = Article.new
=> #<Article:0x0000555d5c5340a8 id: nil, name: nil, content: nil, created_at: nil, updated_at: nil>
pry(main)> 

Geben Sie einen Wert in das Artikelobjekt ein

python


pry(main)> @article.name = "Artikel 1"
=> "Artikel 1"

pry(main)> @article.content = "Der Inhalt des Artikels"
=> "Der Inhalt des Artikels"

Besteht das Artikelobjekt die Validierung?

python


pry(main)> @article.valid?
=> true

Speichern Sie das Artikelobjekt in der DB.

python


pry(main)> @article.save!
   (0.5ms)  BEGIN
  Article Create (8.5ms)  INSERT INTO "articles" ("name", "content", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "Artikel 1"], ["content", "Der Inhalt des Artikels"], ["created_at", "2020-09-26 18:18:00.150412"], ["updated_at", "2020-09-26 18:18:00.150412"]]
   (4.1ms)  COMMIT
=> true

Verbinde dich mit Postgres.

python


docker-compose exec db psql -U postgres -d myapp_development

psql (12.4 (Debian 12.4-1.pgdg100+1))
Type "help" for help.

myapp_development=# 

Liste der Datenbanken anzeigen

python


myapp_development=# \l
                                     List of databases
       Name        |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges   
-------------------+----------+----------+------------+------------+-----------------------
 myapp_development | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 
 myapp_test        | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres          | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0         | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
                   |          |          |            |            | postgres=CTc/postgres
 template1         | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
                   |          |          |            |            | postgres=CTc/postgres
(5 rows)

Zeigen Sie die Tabelle der verbundenen Datenbank an

python


myapp_development=# \d
                  List of relations
 Schema |         Name         |   Type   |  Owner   
--------+----------------------+----------+----------
 public | ar_internal_metadata | table    | postgres
 public | articles             | table    | postgres
 public | articles_id_seq      | sequence | postgres
 public | comments             | table    | postgres
 public | comments_id_seq      | sequence | postgres
 public | schema_migrations    | table    | postgres
(6 rows)

Tabellenspalten anzeigen

python


myapp_development=# \d articles
                                          Table "public.articles"
   Column   |              Type              | Collation | Nullable |               Default                
------------+--------------------------------+-----------+----------+--------------------------------------
 id         | bigint                         |           | not null | nextval('articles_id_seq'::regclass)
 name       | character varying              |           |          | 
 content    | text                           |           |          | 
 created_at | timestamp(6) without time zone |           | not null | 
 updated_at | timestamp(6) without time zone |           | not null | 
Indexes:
    "articles_pkey" PRIMARY KEY, btree (id)

Tabellenspaltendaten anzeigen

python


myapp_development=# select * from articles ;
 id | name  |    content     |         created_at         |         updated_at         
----+-------+----------------+----------------------------+----------------------------
  1 |Artikel 1|Der Inhalt des Artikels| 2020-09-26 18:18:00.150412 | 2020-09-26 18:18:00.150412
(1 row)

Es enthält die von Pry erstellten Daten.

Modellassoziation

Assoziierter Artikel als Elternteil und Kommentar als Kind

Schreiben Sie article.rb wie folgt um

python


class Article < ApplicationRecord
    has_many :comments
end

Schreiben Sie comment.rb wie folgt um

python


class Comment < ApplicationRecord
    belongs_to :article
end

Assoziationsmigrationsdatei hinzufügen

python


docker-compose run web rails g migration Add_Article_Id_To_Comment

Running via Spring preloader in process 68
      invoke  active_record
      create    db/migrate/20200926184159_add_article_id_to_comment.rb

Ändern Sie die unten erstellte Migrationsdatei

Achten Sie auf die Position des Tisches.

python


class AddArticleIdToComment < ActiveRecord::Migration[6.0]
  def change
    add_reference :comments, :article, foreign_key: true
  end
end

Verbinde dich mit Postgres.

python


docker-compose exec db psql -U postgres -d myapp_development

psql (12.4 (Debian 12.4-1.pgdg100+1))
Type "help" for help.

myapp_development=# 


Stellen Sie sicher, dass articles_id zur Kommentartabelle hinzugefügt wird.

python


myapp_development=# \d comments  
                                          Table "public.comments"
   Column    |              Type              | Collation | Nullable |               Default                
-------------+--------------------------------+-----------+----------+--------------------------------------
 id          | bigint                         |           | not null | nextval('comments_id_seq'::regclass)
 comment     | text                           |           |          | 
 created_at  | timestamp(6) without time zone |           | not null | 
 updated_at  | timestamp(6) without time zone |           | not null | 
 article_id  | bigint                         |           |          | 
Indexes:
    "comments_pkey" PRIMARY KEY, btree (id)
    "index_comments_on_articles_id" btree (articles_id)
Foreign-key constraints:
    "fk_rails_d8ed532d4e" FOREIGN KEY (articles_id) REFERENCES articles(id)

Fangen Sie an zu hebeln.

python


comment = Comment.new
=> #<Comment:0x00007f1d8c4f2490 id: nil, comment: nil, created_at: nil, updated_at: nil, article_id: nil>

Kommentare Speichern Sie Daten im Modell.

python


comment.comment = "This is Comment"
=> "This is Comment"

comment.articles_id = 1
=> 1

Überprüfen Sie, ob die vom Modell erstellte Instanz in der Datenbank gespeichert werden kann.

python


comment.valid?
=> true

Speichern Sie die Instanz in der Datenbank.

python


comment.save
   (0.6ms)  BEGIN
  Comment Create (17.2ms)  INSERT INTO "comments" ("comment", "created_at", "updated_at", "article_id") VALUES ($1, $2, $3, $4) RETURNING "id"  [["comment", "This is Comment"], ["created_at", "2020-10-02 12:50:20.046429"], ["updated_at", "2020-10-02 12:50:20.046429"], ["article_id", 1]]
   (3.3ms)  COMMIT
=> true

Erstellen Sie eine Artikelinstanz mit ID1.

python


article = Article.find(1)
  Article Load (3.6ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
=> #<Article:0x00007f1f0c612a38
 id: 1,
 name: "Artikel 1",
 content: "Der Inhalt des Artikels",
 created_at: Sat, 26 Sep 2020 18:18:00 UTC +00:00,
 updated_at: Sat, 26 Sep 2020 18:18:00 UTC +00:00>

Rufen Sie die Kommentardaten ab, die der Instanz von Artikel 1 zugeordnet sind.

python


commnet = article.comments
=>   Comment Load (2.1ms)  SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = $1  [["article_id", 1]]
[#<Comment:0x00007f1f0c81a088
  id: 1,
  comment: "This is Comment",
  created_at: Fri, 02 Oct 2020 12:50:20 UTC +00:00,
  updated_at: Fri, 02 Oct 2020 12:50:20 UTC +00:00,
  article_id: 1>]

Erstellen Sie eine weitere Kommentarinstanz.

python


commnet = Comment.new
=> #<Comment:0x00007f1f0ca3c780 id: nil, comment: nil, created_at: nil, updated_at: nil, article_id: nil>

Führen Sie eine Validierung durch.

python


commnet.valid?
=> false

Erhalten Sie den Fehler zum Zeitpunkt des Validierungsfehlers.

python


commnet.errors
=> #<ActiveModel::Errors:0x00007f1f0caa9d58
 @base=#<Comment:0x00007f1f0ca3c780 id: nil, comment: nil, created_at: nil, updated_at: nil, article_id: nil>,
 @details={:article=>[{:error=>:blank}]},
 @messages={:article=>["must exist"]}>

Mit dem oben genannten D.

Recommended Posts

[Mein Memo] Lass uns mit Pry / DB mit Rails auskommen
Beginnen wir mit der parallelen Programmierung
Erstellen Sie meine Seite mit Rails
Memo mit Struts2 + Ajax zu bekommen
[Schienen] Machen wir einen Unit-Test mit Rspec!
[Rails] Verwalten wir Konstanten mit config gem
Lassen Sie uns mit Rails einen Fehlerbildschirm erstellen
Beginnen wir mit Java-Create a Development Environment ②
Beginnen wir mit Java-Create a Development Environment ①
Holen Sie sich ein untergeordnetes Modell mit Schienen created_at desc scope
Lassen Sie uns eine Suchfunktion mit Rails (Ransack) machen
Vielleicht funktioniert es! Beginnen wir mit Docker!
Rails-Anfänger haben versucht, mit RSpec zu beginnen
Kommen Sie mit Java-Containern in Cloud Run zurecht