LoginSignup
11
7

More than 5 years have passed since last update.

Railsのrendar json:配列を、includesでネストさせる

Last updated at Posted at 2014-11-06

概要

Railsのrendar json:でだす配列を構造として以下の様な感じにネストさせたい。
userは何人かいて、todoがuserに紐づくデータです。

user: [{
    id: 1,
    name: aaaa,
    todo: [
        {id: 1, name: aaaaaaa, del: 1},
        {id: 2, name: eeee, del: 1},
        {id: 3, name: ccccc, del: 0},
        {id: 4, name: hhhhh, del: 0},
        {id: 5, name: kkkkk, del: 0},
    ]
},
{
    id: 2,
    name: aaaa,
    todo: [
        {id: 6, name: jjj, del: 1},
        {id: 7, name: ee, del: 1},
        {id: 8, name: gggg, del: 0},
    ]
},
{
    id: 3,
    name: aaaa,
    todo: [
        {id: 9, name: aaaaaaa, del: 1},
        {id: 10, name: eeee, del: 1},
        {id: 11, name: ccccc, del: 0},
        {id: 12, name: hhhhh, del: 0},
    ]
}
]

userを配列にする

userは、取ってきたいユーザーidで繰り返す。

      users = []
      users.each do |target_ids|
        team_member_info.push(User.where(id: target_ids)[0])
      end

      render json: users.to_json

userに紐づくtodoを配列に組み込む

検索するとき、includesを使います。to_jsonの方にはオプションをつけてあげます。
これにてtodoがuserの配列の中に組み込まれて、お目当ての配列になりました。

      users = []
      users.each do |target_ids|
        team_member_info.push(User.includes(:todos).where.(id: target_ids, "todos.deleted" => 0)[0])
      end

      render json: users.to_json(:include => :todos)

akinomaeniさんに教わりました。いつもありがとうございます。

11
7
1

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
11
7