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

[WIP] Add support for polymorphic associations. #1453

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/active_model/serializer/reflection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class Reflection < Field
#
def build_association(subject, parent_serializer_options)
association_value = value(subject)
reflection_options = options.dup
reflection_options = reflection_options(association_value, options)
serializer_class = subject.class.serializer_for(association_value, reflection_options)

if serializer_class
Expand All @@ -78,6 +78,17 @@ def build_association(subject, parent_serializer_options)

private

def polymorphic_key(assoc_value)
reflection_key = assoc_value.class.model_name
assoc_value.respond_to?(:each) ? reflection_key.plural : reflection_key.singular
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😘 what I need, I'm merging this in a branch of mine 😁

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool, tell me whether this worked! (usage is has_one :addressable, polymorphic: true)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

works like a charm ;)

end

def reflection_options(assoc_value, options)
reflection_options = options.dup
reflection_options[:key] = polymorphic_key(assoc_value) if options[:polymorphic] && !options.key?(:key)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: We might want to make it a ||= in order not to override user-provided options (instead of testing for !options.key?(:key)).

reflection_options
end

def serializer_options(subject, parent_serializer_options, reflection_options)
serializer = reflection_options.fetch(:serializer, nil)

Expand Down