そういうことだったんですね

いろいろ調べたり学んだりしたことを忘れないように書き連ねています

rails - CRUDのまとめ



新規作成

レコードを新規作成する。

create
Entry.create title: "タイトル", body: "本文"
INSERT INTO "entries" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)  [["body", "本文"], ["created_at", Wed, 05 Mar 2014 19:40:52 UTC +00:00], ["title", "タイトル"], ["updated_at", Wed, 05 Mar 2014 19:40:52 UTC +00:00]]
new & save

以下のように、インスタンスを作成後保存する方法でも可能

@entry = Entry.new title: "タイトル", body: "本文"
@entry.save
INSERT INTO "entries" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)  [["body", "本文"], ["created_at", Wed, 05 Mar 2014 19:41:27 UTC +00:00], ["title", "タイトル"], ["updated_at", Wed, 05 Mar 2014 19:41:27 UTC +00:00]]

更新

特定のレコードを更新する

update

クラスメソッド

Entry.update 7, title: "別のタイトル"
UPDATE "entries" SET "title" = ?, "updated_at" = ? WHERE "entries"."id" = 7  [["title", "別のタイトルです"], ["updated_at", Wed, 05 Mar 2014 19:25:53 UTC +00:00]]

インスタンスメソッド

@entry = Entry.find 7
@entry.update title: "別のタイトル"
UPDATE "entries" SET "title" = ?, "updated_at" = ? WHERE "entries"."id" = 7  [["title", "別のタイトル"], ["updated_at", Wed, 05 Mar 2014 19:24:58 UTC +00:00]]
find & update

レコードの属性を作成して更新してもよい

@entry = Entry.find 1
@entry.title = "新しいタイトル"
@entry.save
UPDATE "entries" SET "title" = ?, "updated_at" = ? WHERE "entries"."id" = 11  [["title", "新しいタイトル"], ["updated_at", Wed, 05 Mar 2014 19:47:20 UTC +00:00]]
new & update

まだ保存されていないオブジェクトの場合は、新規作成される

@entry = Entry.new
@entry.update title: "タイトル3"
INSERT INTO "entries" ("created_at", "title", "updated_at") VALUES (?, ?, ?)  [["created_at", Wed, 05 Mar 2014 19:29:09 UTC +00:00], ["title", "タイトル3"], ["updated_at", Wed, 05 Mar 2014 19:29:09 UTC +00:00]]

削除(destroy,delete)

destroy

before_destroy コールバックが呼び出される。
トランザクション内で実行される。
削除したオブジェクトを返す。
オブジェクトはfreezeされるため、再度保存することはできない。
(destroyed? メソッドで確認可能)

クラスメソッド

Entry.destroy 8
DELETE FROM "entries" WHERE "entries"."id" = ?  [["id", 8]]

全レコードを1レコードずつ削除する。
1レコードずつトランザクション内で実行される。

Entry.destroy_all
DELETE FROM "entries" WHERE "entries"."id" = ?  [["id", 9]]
DELETE FROM "entries" WHERE "entries"."id" = ?  [["id", 10]]

インスタンスメソッド

@entry = Entry.find 1
@entry.destroy
@entry.destroyed?  #=> true
DELETE FROM "entries" WHERE "entries"."id" = ?  [["id", 12]]
delete

レコードの削除。
コールバックは呼び出されない。

クラスメソッド

削除したレコード数を返す。

Entry.delete 1
DELETE FROM "entries" WHERE "entries"."id" = 11

全レコードを削除する。

Entry.delete_all
DELETE FROM "entries"

インスタンスメソッド

削除したインスタンスを返す。freezeされるので新規保存は不可能。

@entry = Entfy.find 7
@entry.delete
@entry.destroyed?  #=> true
DELETE FROM "entries" WHERE "entries"."id" = 7


Rubyレシピブック 第3版 303の技

Rubyレシピブック 第3版 303の技