# model作成
$ rails generate model user name:string email:string
# マイグレーションファイル実行(DBに反映)
$ rails db:migrate
$ rails generate migration add_index_to_users_email
$ rails generate migration add_password_digest_to_users password_digest:string
# エラー時のお役立ちコマンド
$ rails generate destoroy user
$ rails db:migrate:reset
##メソッド
new
新しいユーザーオブジェクトを生成
>> user = User.new(name: "Michael Hartl", email: "michael@example.com")
=> #<User id: nil, name: "Michael Hartl", email: "michael@example.com",
created_at: nil, updated_at: nil>
valid?
オブジェクトが有効かどうか
>> user.valid?
true
save
DBにUserオブジェクトを保存
>> user.save
(0.1ms) SAVEPOINT active_record_1
SQL (0.8ms) INSERT INTO "users" ("name", "email", "created_at",
"updated_at") VALUES (?, ?, ?, ?) [["name", "Michael Hartl"],
["email", "michael@example.com"], ["created_at", "2019-08-22 01:51:03.453035"],
["updated_at", "2019-08-22 01:51:03.453035"]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> true
create
モデルの生成(new)と保存(save)を同時に行う
>> User.create(name: "A Nother", email: "another@example.org")
#<User id: 2, name: "A Nother", email: "another@example.org", created_at:
"2019-08-22 01:53:22", updated_at: "2019-08-22 01:53:22">
# 変数fooに代入
>> foo = User.create(name: "Foo", email: "foo@bar.com")
#<User id: 3, name: "Foo", email: "foo@bar.com", created_at: "2019-08-22
01:54:03", updated_at: "2019-08-22 01:54:03">
destroy
createの逆で削除(ただしメモリには残る)
>> foo.destroy
(0.1ms) SAVEPOINT active_record_1
SQL (0.2ms) DELETE FROM "users" WHERE "users"."id" = ? [["id", 3]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> #<User id: 3, name: "Foo", email: "foo@bar.com", created_at: "2019-08-22
01:54:03", updated_at: "2019-08-22 01:54:03">
find
, find_by
オブジェクトを検索
#エラー出したい場合
>> User.find(1)
=> #<User id: 1, name: "Michael Hartl", email: "michael@example.com",
created_at: "2019-08-22 01:51:03", updated_at: "2019-08-22 01:51:03">
# 属性(email)で検索。エラー出さないで表示
>> User.find_by(email: "michael@example.com")
=> #<User id: 1, name: "Michael Hartl", email: "michael@example.com",
created_at: "2019-08-22 01:51:03", updated_at: "2019-08-22 01:51:03">
first
DBの最初のユーザー
>> User.first
=> #<User id: 1, name: "Michael Hartl", email: "michael@example.com",
created_at: "2019-08-22 01:51:03", updated_at: "2019-08-22 01:51:03">
all
DB全てのUserオブジェクト
>> User.all
=> #<ActiveRecord::Relation [#<User id: 1, name: "Michael Hartl", email:
"michael@example.com", created_at: "2019-08-22 01:51:03", updated_at:
"2019-08-22 01:51:03">, #<User id: 2, name: "A Nother", email:
"another@example.org", created_at: "2019-08-22 01:53:22", updated_at:
"2019-08-22 01:53:22">]>
update
オブジェクトを更新
>> user.update(name: "The Dude", email: "dude@abides.org")
=> true
>> user.name
=> "The Dude"
>> user.email
=> "dude@abides.org"
# 検証を回避して更新したい
>> user.update_attribute(:name, "El Duderino")
=> true
>> user.name
=> "El Duderino"
errors
エラー内容表示
>> user = User.new(name: "", email: "michael@example.com")
>> user.valid?
=> false
>> user.errors.full_messages
=> ["Name can't be blank"]