vt-elixir / ja_serializer

JSONAPI.org Serialization in Elixir.
Other
640 stars 148 forks source link

included records attributes are empty when serializing with has_many #286

Closed ashrafhasson closed 5 years ago

ashrafhasson commented 6 years ago

In ja_serializer 0.12.0, it appears that specifying include: true for a has_many relation does include the related data in the relationships but the included records have an empty attributes map.

defmodule App.TransactionView do
  use App.Web, :view
  use JaSerializer.PhoenixView

  attributes [:transaction_date, :transaction_type, :status, :statement, :inserted_at]

  has_many :entries,
    serializer: App.EntrySerializer,
    include: true

end

defmodule App.EntrySerializer do
  use JaSerializer

  # matches only when POSTing
  def attributes(entry, conn = %{assigns: %{credit_entry: credit_entry, debit_entry: debit_entry}}) do
    case entry do
      %{operation: "credit"} ->
        super(entry, conn)
        |> Map.take([:amount, :operation])
        |> Map.put_new(:__id__, Map.get(credit_entry, "__id__"))
      %{operation: "debit"} ->
        super(entry, conn)
        |> Map.take([:amount, :operation])
        |> Map.put_new(:__id__, Map.get(debit_entry, "__id__"))
    end
  end

  def attributes(entry, conn) do
    super(entry, conn)
  end
end

When not specifying include: true or setting it to false, no included is rendered and the relationships is also impacted where it contains an empty map for the entries.

What wrong am I doing here in this serializer? Appreciate any help.

Thanks!

ashrafhasson commented 6 years ago

It turns out using the related model's PhoenixView that is in turn enabled to use JaSerializer.DSL behaviour, instead of a custom serializer, is a better way to make this work.

I believe the documentation can be improved slightly to cover nested relationships in the context of a Phoenix app.

Thanks for the awesome lib!

beerlington commented 5 years ago

Closing this issue since it seems like user error and it's not really clear how the docs could be improved. Happy to make updates to the docs if there's anything specific that should be addressed.