Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible to specify serializer to use for relationship of different name? #134

Open
mecampbellsoup opened this issue Oct 13, 2020 · 3 comments

Comments

@mecampbellsoup
Copy link

mecampbellsoup commented Oct 13, 2020

I have a JobSerializer that has 2 relationships - the hosted file, and outputs.

(This is because a job is rendered from a file that the user uploaded - the "hosted file" - and the result of running the job are output files - "outputs".)

Both the singular hosted file, and the plural output, relationships are modeled by a class called HostedFile (not backed by ActiveRecord, but rather backed by the filesystem).

I want to use the same serializer for both relationships, i.e. API::V1::HostedFileSerializer.

Is it possible to specify the serializer to use for a relationship, e.g.:

class API::V1::JobSerializer < API::V1::BaseSerializer
  include JSONAPI::Serializer

  has_one :hosted_file
  has_many :outputs, serializer: API::V1::HostedFileSerializer

Ideally I could then do something like the following and both relationships would be serialized using the API::V1::HostedFileSerializer:

class JobsController < ApplicationController
  def show
    serialize_model job, include: ['outputs', 'hosted-file']
  end
end
@mecampbellsoup
Copy link
Author

mecampbellsoup commented Oct 13, 2020

BTW, I tried doing the following as well:

# Added to bottom of `api/v1/hosted_file_serializer.rb` file
API::V1::OutputSerializer = API::V1::HostedFileSerializer

@digaoddc
Copy link

I agree, It'd be great to specify the serializer in the method has_many and has_one.

like this:

has_one :foo, serializer API::V1::Foo
has_many :bar, serializer: API::V1::Bar

@mecampbellsoup
Copy link
Author

FWIW, I ended up defining Job#outputs to return an array of HostedFile instances, and this library seems to look at the type/class of the relationship... long story short, my JobSerializer#outputs relationship is correctly serialized using my HostedFileSerializer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants