Serialize JSON Association for Model Children
I am using active model serializers for my API. I have a model (Task) that has many sub-tasks (always Task model) called children. I am doing this recursive has_many association thanks to ancestor birth ( https://github.com/stefankroes/ancestry )
It works well enough, but I have this problem: The task has a user relationship, but while the active serializer models export the user for the main object, it does not display the user's details for all children. This is my serializer:
class TaskSerializer < ActiveModel::Serializer
attributes :id, :name, :details, :user_id
belongs_to :user
has_many :children
end
This is my controller:
class Api::V1::TasksController < Api::V1::BaseController
respond_to :json
def index
@tasks = current_user.company.tasks
respond_with @tasks, location: nil
end
end
And this is my model:
class Task < ActiveRecord::Base
has_ancestry
belongs_to :user
end
I also tried to do this in my model:
class Api::V1::TasksController < Api::V1::BaseController
respond_to :json
def index
@tasks = current_user.company.tasks
render json: @tasks,
each_serializer: TaskSerializer,
status: :ok
end
end
But doesn't work ... I have user data for the parent but not the children (where it only shows the user_id, without the whole User object)
Any suggestions?
+3
source to share