1

I have this piece of code in my update.json.jbuilder

json.data do
  json.(@user_group, :id, :name, :description)
  json.users @user_group.users, :id, :name
  json.roles @user_group.roles, :id, :name
end

which gives me this JSON:

{
   "data":{
      "id":95,
      "name":"Management group",
      "description":"This is management group",
      "users":[
         {
            "id":10,
            "name":"Test User"
         }
      ],
      "roles":[
         {
            "id":1,
            "name":"FULL ACCESS (TEMPORARY)"
         }
      ]
   }
}

How do I wrap "data" in array to something like this, please?

{
   "data": [ 
    {
      "id":95,
      "name":"Management group",
      "description":"This is management group",
      "users":[
         {
            "id":10,
            "name":"Test User"
         }
      ],
      "roles":[
         {
            "id":1,
            "name":"FULL ACCESS (TEMPORARY)"
         }
      ]
   }
 ]
}

Notice [ ] after first and last { } So far I've been trying to implement json.array!, but no luck as it throws me ActionView::Template::Error (undefined method map which means I'm trying to put together something which probably does not fit as mentioned here.

1 Answer 1

1

With child! method it seems to be this simple:

json.data do
  json.child! do
    json.(@user_group, :id, :name, :description)
    json.users @user_group.users, :id, :name
    json.roles @user_group.roles, :id, :name
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.