I think the problem is that by default to_json does not include related objects. Try this:
render json: Task.where(parent_id: 0).includes(:children).to_json(include: :children)
문제
I'm writing a REST api to return tasks lists.
Here's my set of data:
id | name | parent_id
1 | Ride a horse | 0
2 | Eat tacos | 0
3 | Get some cash| 2
A Task can have subtasks so I made my model self joined:
class Task < ActiveRecord::Base
belongs_to :parent, :class_name => 'Task', :foreign_key => 'parent_id'
has_many :children, :class_name => 'Task', :foreign_key => 'parent_id'
end
I then eager load my tasks
def index
respond_with Task.where(parent_id: 0).includes(:children)
end
Here's what the console shows:
Task Load (0.4ms) SELECT
tasks
.* FROMtasks
WHEREtasks
.parent_id
= 0Task Load (0.3ms) SELECT
tasks
.* FROMtasks
WHEREtasks
.parent_id
IN (1, 2)
So it actually does run the query, however, it doesn't put the result in my object. The only 2 tasks showing in the response are the ones where parent_id = 0.
Am I doing something wrong? I'd like this subtask to be in the response as well.
해결책
I think the problem is that by default to_json does not include related objects. Try this:
render json: Task.where(parent_id: 0).includes(:children).to_json(include: :children)