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

Include ActiveModel::Serializer associations #382

Closed
wants to merge 2 commits into from

Conversation

kyreeves
Copy link

Q A
Bug fix? yes
New feature? no
BC breaks? no
Related Issue Fix #346
Need Doc update no

Describe your change

Calling the attributes method on an instance of a ActiveModel::Serializer class does not include associations. This fixes the issue by calling the as_json method instead.

What problem is this fixing?

When using an ActiveModel Serializer to serialize your model, associations are not included.

@yanismydj
Copy link

I use AMS associations extensively -- thanks for doing this, I'd love to see this get merged!

@yanismydj
Copy link

hey @julienbourdeau - any chance you can review/approve this? It would help me & @ivancevich greatly!

@chloelbn
Copy link
Contributor

Hi @yanismydj and @kyreeves! I will deal with this PR this week :) Thanks for pinging us

@siddharth28
Copy link

@chloelbn / @julienbourdeau any update on this?

@Haroenv
Copy link

Haroenv commented Sep 6, 2021

Changing from reading only :attributes to reading all relationships would be a breaking change. Do you see a way in which this would be an option to make it non-breaking? Thanks!

@kyreeves kyreeves closed this Mar 8, 2024
@coatezy
Copy link

coatezy commented Jul 3, 2024

Hi, I know this is an old PR but I wanted to share my work around for this as it may help others in the future.

Instead of directly passing an active model serializer to use_serializer I pass it a "delegator" class that allows me to return the serialized json object with nested associations.

First we create a delegator

class Search::SerializerDelegator
  attr_accessor :object

  def attributes(*attrs)
    serializer.new(object).as_json
  end

  def initialize(object)
    @object = object
  end

  private

  def serializer
    "Search::Serializers::#{object.class.name}Serializer".constantize
  end
end

We then use the delegator instead of using the Active Model Serializer directly

  algoliasearch do
    use_serializer Search::SerializerDelegator
    searchableAttributes ["title" "body"]
  end

The delegator initializes the matching model serializer and then calls #as_json instead of #attributes.

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

Successfully merging this pull request may close these issues.

New use_serializer feature doesn't include associations
6 participants