Skip to content

Define a context for a nested association #1554

@willcosgrove

Description

@willcosgrove

Expected behavior vs actual behavior

From the serializer of an association, I would like to access the object of the parent serializer.

Steps to reproduce

Say we have three models, Ballot, Candidate, and Vote. Candidates and Ballots have a many to many relationship. Votes belong to a Ballot and a Candidate. I'm writing a Ballot serializer that has_many :candidates. I'm then making use of the subclassed serializer to have a custom CandidateSerializer. Inside the CandidateSerializer I want an attribute that represents the number of votes for that Candidate on that Ballot. But to write that method, I need to know which ballot this is being serialized for. Is this possible somehow?

I have managed to hack it by removing the association on the BallotSerializer and just defining a candidates attribute that returns an array of hashes, and build the candidate that way. But having the child serializer seems a lot cleaner. Is there anyway for me to pass that context of which ballot I'm serializing this candidate for?

Environment

ActiveModelSerializers Version (commit ref if not on tag): a6c6979

Output of ruby -e "puts RUBY_DESCRIPTION": ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]

OS Type & Version: OS X 10.11.3

Integrated application and version (e.g., Rails, Grape, etc): Rails 5.0.0.beta2

Additonal helpful information

I am currently using the default attributes adapter.

Let me know if there's anything I can post to make the above situation more clear. Thanks for your help!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions