panko_serializer icon indicating copy to clipboard operation
panko_serializer copied to clipboard

Has_many method 'xxx_ids'

Open BorisBresciani opened this issue 5 years ago • 4 comments

Hello,

Variables of type 'xxx_ids' (has_many) built automatically by ActiveRecord do not work in attributes mode

Exemple:

This example works

Model:

has_many :pankos

Serializer:

attributes :panko_ids
def panko_ids
  object.panko_ids
end

###############

This example does not work

Model:

has_many :pankos

Serializer:

attributes :panko_ids #return always null

However the variable panko_ids is well regarded as an attribute because I can do record.panko_ids or record.send(:panko_ids)

Ruby: 2.5.1 Rails: 5.2.1

Thx :)

BorisBresciani avatar Nov 21 '18 21:11 BorisBresciani

@BorisBresciani I can add support for has_many :pankos, embed: :ids in serializer like AMS.

wdyt?

yosiat avatar Nov 25 '18 19:11 yosiat

It is a good idea or if not to do as simple attributes without specifying "has_many" like my example

BorisBresciani avatar Nov 25 '18 19:11 BorisBresciani

It's simple to do embed because at serializer definition time I don't know which model is serialized in advance so I can't tell if panko_ids is field or method and detecting this at runtime can be a huge performance loss.

I have two options to tackle this:

  • Move to strict serializes and don't allow polymorphic serializers, so in addition to attributes, you will specify model Post - and I can tell automatically which method it is, gather type information etc.
  • At runtime detect which model I am serializing and cache results of attributes mapping per serializer.

Both solutions will take some time to develop if you can wait two weeks (at max), I will implement them now and in the meanwhile you will do:

attributes :panko_ids
def panko_ids
  object.panko_ids
end

or

attributes :panko_ids
delegate :panko_ids to: :object

yosiat avatar Nov 25 '18 21:11 yosiat

Hi,

The second solution seems better

BorisBresciani avatar Nov 26 '18 10:11 BorisBresciani