[My memo] Let's get along with Pry / DB with Rails

Introduction

When operating DB using Pry in Rails Leave the necessary commands and ideas as a personal memo.

environment

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

Environment

The Vue Rails 6 environment construction using Docker is summarized below. Link: How to link Rails6 Vue (from environment construction)

Model and DB migration related

I will raise the Docker container.

python


Docker-compose up

Creating an Article model

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

Comment Creating a model

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

Reflection 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 status check

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

Check the version in 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

If Docker-compose exec web rails db: rollback STEP = 2, it will be [+1] down.

In other words Docker-compose exec web rails db:rollback STEP=1 When Docker-compose exec web rails db:rollback Is the same

python


Docker-compose exec web rails db:rollback

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

DB status check

It is necessary to delete the migration file and add the DB column at the time of down. Generally, a migration file is created and described separately for adding a DB column.

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 db: migrate and put it back.

Launch Pry

Start 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)> 

Create a new article object

python


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

Put a value in the article object

python


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

pry(main)> @article.content = "The content of the article"
=> "The content of the article"

Does the article object pass validation?

python


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

Save the article object in the 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", "Article 1"], ["content", "The content of the article"], ["created_at", "2020-09-26 18:18:00.150412"], ["updated_at", "2020-09-26 18:18:00.150412"]]
   (4.1ms)  COMMIT
=> true

Connect to 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=# 

View list of databases

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)

Display the table of the connected DB

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)

Show table columns

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)

View table column data

python


myapp_development=# select * from articles ;
 id | name  |    content     |         created_at         |         updated_at         
----+-------+----------------+----------------------------+----------------------------
  1 |Article 1|The content of the article| 2020-09-26 18:18:00.150412 | 2020-09-26 18:18:00.150412
(1 row)

It contains the data created by Pry.

Model association

Associate Article as a parent and Comment as a child

Rewrite article.rb as below

python


class Article < ApplicationRecord
    has_many :comments
end

Rewrite comment.rb as below

python


class Comment < ApplicationRecord
    belongs_to :article
end

Added association migration file

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

Modify the created migration file below

Pay attention to the position of the table, singular and plural.

python


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

Connect to 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=# 


Make sure articles_id is added to the comments table.

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)

Start pry.

python


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

comments Store data in the model.

python


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

comment.articles_id = 1
=> 1

Validate whether the instance created by the model can be stored in the DB.

python


comment.valid?
=> true

Save the instance in the database.

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

Create an Article instance with 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: "Article 1",
 content: "The content of the article",
 created_at: Sat, 26 Sep 2020 18:18:00 UTC +00:00,
 updated_at: Sat, 26 Sep 2020 18:18:00 UTC +00:00>

Get the Comments data associated with the Article instance with ID1.

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>]

Create another Comment instance.

python


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

Perform validation.

python


commnet.valid?
=> false

Get the error at the time of validation error.

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"]}>

With the above D

Recommended Posts

[My memo] Let's get along with Pry / DB with Rails
How to get along with Rails
How to get along with Rails
Let's get started with parallel programming
[My style] rails Initial setting memo
Create My Page with Rails devise
Memo to get with Struts2 + Ajax
Let's unit test with [rails] Rspec!
Get the value of enum saved in DB by Rails with attribute_before_type_cast
[Rails] Let's manage constants with config gem
Let's make an error screen with Rails
Let's get started with Java-Create a development environment ②
Let's get started with Java-Create a development environment ①
Get child model with rails created_at desc scope
Let's make a search function with Rails (ransack)
Maybe it works! Let's get started with Docker!
Rails beginners tried to get started with RSpec
Get along with Java containers in Cloud Run