Home>
I want to mold multiple instance variables with jbuilder as follows.
Nested with two types of objects.

{tasks: [{"id": 1, "name": "hoge", "is_done": true}, {"id": 2, "name": "huga", "is_done" : false}, {"id": 3, "name": "hogehuga", "is_done": true}], done_tasks: [{"id": 1, "name": "hoge", "is_done": true }, {"id": 3, "name": "hogehuga", "is_done": true}]}
Model Task model

id: int
name: string
is_done: boolearn

Source Controller
def index
  @tasks = Task.order ('updated_at DESC')
  @done_tasks = Task.where (is_done: true)
end

I tried this pattern (@done_tasks class is Array)

@tasks = Task.order ('updated_at DESC')
 @done_tasks = @ tasks.select {| task | task.is_done}
Tried with jbuilder
json.array! @tasks,: id,: name,: is_done,: created_at,: updated_at
end
json.done_tasks do
  json.array! @done_tasks,: id,: name,: is_done,: created_at,: updated_at
end
json.set! tasks do
    json.array! @tasks,: id,: name,: is_done,: created_at,: updated_at
  end
  json.set! done_tasks do
    json.array! @done_tasks,: id,: name,: is_done,: created_at,: updated_at
  end
json.set!: tasks do
    json.array! @tasks do | task |
      json.extract! task,: id,: name,: is_done,: created_at,: updated_at
    end
end
json.set!: done_tasks done_tasks
  json.array! @done_tasks do | done_task |
    json.extract! done_task,: id,: name,: is_done,: created_at,: updated_at
  end
end

etc ...

Current status

When you hit the corresponding curl command, it will be as follows or HTML will be returned.

{"tasks": [{"id": 1, "name": "hoge", "is_done": true}, {"id": 2, "name": "huga", " is_done ": false}, {" id ": 3," name ":" hogehuga "," is_done ": true}]," done_tasks ": []}


↑ done_tasks becomes an empty array

I want to tell me

・ Method when@tasksand@done_tasksare both ActiveRecord
@done_tasksonly for Array

  • Answer # 1

    When I applied rails restart, the changes of jbuilder were reflected and it worked.
    It seems that the same result was repeated many times because the change was not reflected.