動作確認環境
- Windows10(x64)
- rails 6.1.7
- ruby 3.0.4p208
モデルを定義してみる
プロジェクトのルートディレクトリへ移動し、「rails g model ToDoList title:string content:string create_at:date update_at:date」のように実行してみる
→今回の場合は添付オレンジ枠の3つのファイルが生成された。
※上記のcreate_at:date update_at:dateの箇所は設定しなくても勝手に作ってくれるので不要だった

※rails g model コマンドの詳細は https://railsdoc.com/page/rails_generate_model を参照
生成された各ファイルの内容↓
class ToDoList < ApplicationRecord
end
class CreateToDoLists < ActiveRecord::Migration[6.1]
def change
create_table :to_do_lists do |t|
t.string :title
t.string :content
t.date :create_at
t.date :update_at
t.timestamps
end
end
end
require 'rails_helper'
RSpec.describe ToDoList, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
プロジェクトのルートディレクトリで「bundle exec rails db:migrate」を実行する
※データベースをまだ作成していない場合は先にbundle exec rails db:createが必要になるはず

→pgAdmin4で確認すると、テーブルが生成されていることが分かる。

モデルのインスタンスを保存してみる
rails c で、作成したモデルのインスタンスを生成してみる
saveメソッドを実行すると、テーブルにレコードを保存できる
(newでモデルのインスタンスを生成し、idを設定、saveメソッドでDBへ保存している)


モデルを検索してみる
まず以下のようなレコードを準備する

rails c を起動し、findメソッドを使えば、引数で指定したプライマリーキーに合致するレコードを取得することができる。

プライマリーキーではなく、その他の属性を検索条件に指定したい場合はfind_byメソッドを使えば良い。

複数のレコードを検索する場合は、whereメソッドを用いる
