Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize JSON association for children of a model

I'm using active-model-serializers for my API. I have a model (Task) that has many subtasks(always Task model), called children. I do this recursive has_many association thanks to ancestry gem (https://github.com/stefankroes/ancestry)

It works all enough well, but I have this problem: Task has an association with User, but while active-model-serializers, export user for the main object, it doesn't show user details for also 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've 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've the user details for the parent object, but not for the children(where he only show me user_id, without all User object)

Any suggestions ?

like image 500
Richard Avatar asked Oct 31 '22 05:10

Richard


1 Answers

Have you tried adding a serializer for the Children model or querying them as a explicit attribute like so?

class TaskSerializer < ActiveModel::Serializer
  attributes :id, :name, :details, :user_id, :children

  def children
     object.children
  end    
end
like image 193
Sam Figueroa Avatar answered Nov 15 '22 07:11

Sam Figueroa