1
0

More than 3 years have passed since last update.

初めてのRuby On Rails その2(DB編)

Last updated at Posted at 2021-02-27

テーブル作成手順

1.データベースに変更を指示するファイルを作成

マイグレーションファイルと呼ばれるデータベースに変更を指示するファイルを作成する

今回はpostsテーブルを作成する例を見てみる
この場合、Postと単数形にする

ターミナル
rails g model Post content:text

Post:モデル名
content:カラム名
text:データ型

以下の2ファイルが作成される

ツリー構造

 ├ app/
 │ └ models/
 │    └ post.rb
 ├ db/
   └ migrate/
      └ 20210226224717_create_posts.rb

post.rb

class Post < ApplicationRecord
end
20210226224717_create_posts.rb

class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.text :content

      t.timestamps
    end
  end
end

2.データベースに変更を反映

ターミナル
rails db:migrate

自動で生成されるカラム
id , created_at , updated_at

rails console

後述するテーブルへのデータ保存で使うので記載しておく

開始する場合
ターミナル
rails console

対話型でコマンドを実行できるようになる

終了する場合
ターミナル
quit

テーブルに投稿データを保存しよう

手順

  1. new メソッドで Post モデルのインスタンスを作成
  2. posts テーブルに保存

1. インスタンスを作成

ターミナル
rails console
> post = Post.new(content:"Hello world")
> post2 = Post.new(content:"Hello world 2")
> post3 = Post.new(content:"Hello world 3")

2. 保存

DBに3つのデータが挿入される

ターミナル
> post.save
> post2.save
> post3.save

データ取得

最初のデータを取り出す

postsテーブルの最初のデータを取得

ターミナル
> post = Post.first
> post.content
=> "Hello world"

すべてのデータを取り出す

postsテーブルの全データを配列で取得
allメソッドを用いる

ターミナル
> posts = Post.all
> posts[1].content
=> "Hello world 2"

特定のデータを取り出す

postsテーブルの条件を指定した特定のデータを取得
find_byメソッドを用いる

ターミナル
> post = Post.find_by(id: 3)
> post.content
=> "Hello world 3"

並び替えた状態でデータを取り出す

orderメソッドを用いる
desc:降順、asc:昇順

ターミナル
> posts = Post.all.order(created_at: :desc)

データ更新

①編集したいデータを取得
②そのデータのcontentの値を上書き
③データベースに保存

ターミナル
> post = Post.find_by(id: 3)
> post.content = "Rails"
> post.save

上記のタイミングで、updated_atカラムの値がデータを更新したときの時刻に更新される

データ削除

ターミナル
> post = Post.find_by(id: 3)
> post.destroy

まとめ

DBの基礎知識があれば、特に難しいことはなかった。
SQLを書かないでデータ挿入、取得するのは少し違和感があった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0