1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ActiveModelSerializerのserializerとeach_serializerの違い

Last updated at Posted at 2021-09-27

ActiveModelSerializerとは

RailsでAPIを作る時、 JSON形式(わかりやすく)にしてくれるgemのことです。

serializeを使うとき

例えばstaff一覧をコントローラーで取得する時
これはあくまで例です。

def index
      @staff = Staff.new
      render json: staff, serializer: StaffSerializer
    end

serializerと書くとStaffSerializerを呼び出してくれる。
これはstaff1人を呼び出す時に使う。

each_serializeを使うとき

staff詳細を取得する時

def show
      @staffs = Staff.all
      render json: staffs, each_serializer: StaffSerializer
    end

each_serializerを使うときは、複数取得したいときに使います。

他にもcreateやupdateで1人ではなく複数を取得するときに使います。

簡単な記事だったのとコードはあくまで一例ですのでご了承ください。

⚫︎参考資料
https://lhiroki1205.hatenablog.com/entry/2019/08/25/151413
https://stackoverflow.com/questions/53587217/active-model-serializer-each-serializer-vs-serializer
https://qiita.com/Hashimoto-Noriaki/items/91c2bb94bce87495193e

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?