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】includeオプションの使い方

Posted at

inludeオプション

オブジェクトの関連付けをレンダリングできる。

postに関連づいているpostの著者、コメント、コメントを書いた人を出力できる。

render json: posts,
       include: 'author,comments,comments.author'

多分こんな感じで返ってくるはず。

=> {
"id"=>222,
"author"=>"kato",
"description"=>"ccccccccccccccccccccccccccccccccc",
"created_at"=>"2022-03-07T21:07:22.643+09:00",
"commments"=>
  [{"id"=>1003,
   "content"=>"aaaaaaaaaaaaaaaaaaaaaaa"
   "author"=>"fugafuga"]
}

Serializerにアソシエーション書けばワイルドカードでも同じようにレンダリングできる。

posts_controller.rb
render json: posts,
       include: '**'
post_serializer.rb
class PostSerializer < ActiveModel::Serializer
  attributes :id, :description, :created_at

  belongs_to :author
  has_many :comments
end

Serializerにアソシエーション書いてしまえば、includeで関連先を明記しなくてもよさそう…

参考

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?