fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

Set belongs_to key dynamically

Open jaquesdias opened this issue 6 years ago • 3 comments

Hi everybody,

Anyone already tried to change the belongs_to key name dynamically? Something like:

class MediaSerializer
  include FastJsonapi::ObjectSerializer

  attributes :filename, :content_type, :record_type, :record_id

  belongs_to :record, if: Proc.new { |record| record.record_type === 'Product' ? { key: :product } : { key: :category }  }
end

And relationship would be like:

belongs_to :record, key: :product

Thanks for the awesome gem!

jaquesdias avatar Jan 08 '19 16:01 jaquesdias

I'm not sure if this is what you want but it looks like you've got a polymorphic relationship there. If that's the case you can do:

belongs_to :record, polymorphic: {
  Product => :product,
  Category => :category
}

This sets the record_type so might not be what you want but thought I'd just mention.

PhilT avatar Jan 10 '19 10:01 PhilT

Exactly @PhilT. It changes the record_type but I really need to change the key. I hope someone knows a way to change it.

jaquesdias avatar Jan 10 '19 14:01 jaquesdias

The source code is not that hard to understand. I've modified it myself to handle pluralization. See the bottom of this issue https://github.com/Netflix/fast_jsonapi/issues/301 for example code.

You might be able to code something similar to the polymorphic option but for keys.

PhilT avatar Jan 10 '19 21:01 PhilT