LoginSignup
1
0

More than 1 year has passed since last update.

[初心者log]Rails API 複数Modelの情報をjson型で返す方法

Posted at

本記事の目的

Rails(APIモード) + Reactで開発をしている最中、Post一覧表示にUserのAvatarを付与したいと考え、やり方を調べたのでまとめます。

失敗例

posts_controller.rb
class PostController < ApplicationController

def index
   posts = Post.all
   hash = {}
   posts.each{|post|
     hash[post.id] = {post: post, user: post.user}
   }
   render json: { status: 200, posts: hash }
 end

#以下略

これだと返ってくる値がハッシュになり、React側で

posts.length > ? (
  //処理1
  ) : (
  //処理2
  )

といった記述ができなくなります。

成功例

posts_controller.rb
class PostController < ApplicationController

def index
    posts = Post.all
    array = []
    posts.each{|post|
      array.push({post: post, user: post.user})
    }
    render json: { status: 200, posts: array }
  end

配列型にしてそこにpushすればReact側での処理もスムーズに進みました。

N+1問題についてはまた次回まとめてみようと思います。

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