Frage

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.* FROM tasks WHERE tasks.parent_id = 0

Task Load (0.3ms) SELECT tasks.* FROM tasks WHERE tasks.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.

War es hilfreich?

Lösung

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top