Can Jason.Encoder serialize nested ecto objects

I have this association

  @derive {Jason.Encoder,
  only: [
    :id,
    :title,
    :user
  ]}

  schema "staff" do
    field(:title, :string)

    timestamps()

    belongs_to(:user, Realest8.Accounts.User)
  end

Though I am trying to get user with associated roles

  def list_staffs_by_organization(organization_id) do
    from(s in Staff,
      where: s.organization_id == ^organization_id
    )
    |> Repo.all() |> Repo.preload([{:user, [:roles]}])
  end

I am getting staff details and a nested user object but roles are not included.

Maybe try this?

Repo.preload(user: :roles)

And: you’re sure the user has roles associated at all?

Does the User module have a @derive for Jason.Encoder?

Thanks guys…

This definition worked for me

  def list_staffs_by_organization(organization_id) do
    from(s in Realest8.Staff.Staff,
      where: s.organization_id == ^organization_id,
      preload: [user: [:organization, :roleUsers]]
    )
    |> Repo.all()

  end

I was missing @derive in the roles module.