Set belongs_to key dynamically
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!
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.
Exactly @PhilT. It changes the record_type but I really need to change the key. I hope someone knows a way to change it.
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.