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

undefined method serialize_to_hash ... what's happend #1149

Open
5 tasks
ohimy opened this issue Feb 6, 2018 · 27 comments
Open
5 tasks

undefined method serialize_to_hash ... what's happend #1149

ohimy opened this issue Feb 6, 2018 · 27 comments

Comments

@ohimy
Copy link

ohimy commented Feb 6, 2018

This issue is a (choose one):

  • Problem/bug report.
  • Feature request.
  • [#] Request for support. Note: Please try to avoid submitting issues for support requests. Use Gitter instead.

Checklist before submitting:

  • I've searched for an existing issue.
  • I've asked my question on Gitter and have not received a satisfactory answer.
  • I've included a complete bug report template. This step helps us and allows us to see the bug without trying to reproduce the problem from your description. It helps you because you will frequently detect if it's a problem specific to your project.
  • [ # ] The feature I'm asking for is compliant with the JSON:API spec.

Description

Choose one section below and delete the other:

Bug reports:

Please review Did you find a bug? and replace this content with a brief summary of your issue. If you can't submit a bug report template please be as thorough as possible when describing your your description. It's helpful to indicate which version of ruby and the JR gem you are using.

Features:

Please replace this line with a clear writeup of your feature request. Features that break compliance with the JSON:API spec will probably be closed.

@senid231
Copy link
Contributor

senid231 commented Feb 9, 2018

@ohimy we can't help you if you don't provide more details

@butchmarshall
Copy link
Contributor

butchmarshall commented May 4, 2018

In the documentation under serializer it has JSONAPI::ResourceSerializer.new(PostResource).serialize_to_hash(PostResource.new(post, context))

Try it. You now get this error on master branch:

undefined method serialize_to_hash' for #JSONAPI::ResourceSerializer:0x00000003c50280`

It looks like this commit (bdcbf61) completely removes the method from the ResourceSerializer? It also comments out / removes all the unit tests associated with the method.

It's not clear what new method (if any) replaces the old one either...

More than 5000+ lines of changes with no unit tests and comments that say: # ToDo: Revisit these tests. and # ToDo: Rework these tests

I would not consider master stable after seeing this :)

Any update to how this is supposed to work @lgebhardt ?

@eduscrakozabrus
Copy link

Today i have this is error on version 0.10.0

@jagthedrummer
Copy link
Contributor

Yep, just ran into this when trying to upgrade. The docs and the code definitely don't seem to agree.

backspace added a commit to backspace/waydowntown-server that referenced this issue Nov 24, 2019
I switched away from JSONAPI::Resources because I felt like
I would need custom actions and I couldn’t figure out how
to serialize manually à la serialize_to_hash:
cerebris/jsonapi-resources#1149
@vestedpr-dev
Copy link

vestedpr-dev commented Dec 17, 2019

Thank you for creating jsonapi-resources. Can you give us any guidance on how to upgrade, if we are dependent on the old serialize_to_hash method which is documented here: https://jsonapi-resources.com/v0.10/guide/serializer.html ?

It seems, we can still accomplish something similar by using serialize_resource_set_to_hash and passing in a resource_set? If I have a JSONAPI::Resource object, how do I got about getting that into a JSONAPI::ResourceSet? It looks like I can do it, but I need a resource_id_tree?

It's quite a nice thing to be able to use jsonapi-resources to serialize to JSON since, sometimes I want to be able to do things with my objects' JSON on the server, apart from the API. Since jsonapi-resources combines the API and the serializing, this has always been an attractive aspect of your library.

This is how I used to do it:

module Api
  class ApiSerializer

    def initialize(stuff, context = {})
      @context = context

      if stuff.is_a?(ActiveRecord::Relation)
        @models = stuff
      elsif stuff.is_a?(ActiveRecord::Base)
        @models = [stuff]
      else
        @models = stuff
      end
    end

    def resources
      if @resources
        @resources
      else
        @models.collect do |p|
          resource_klass.new(p, @context)
        end
      end
    end

    def json
      json = { data: [] }

      resources.each do |resource|

        cache_key = "api-serializers/#{resource_klass_name}-#{resource._model.id}/#{resource._model.updated_at.try(:to_s, :db)}"
        resource_json = Rails.cache.fetch(cache_key) do
          JSONAPI::ResourceSerializer.new(resource_klass).serialize_to_hash(resource)
        end

        json[:data].push resource_json[:data]
      end

      json
    end

    private

    def resource_klass
      resource_klass_name.constantize
    end

    # Mirroring JSONAPI::Resources -- see https://github.com/cerebris/jsonapi-resources/blob/v0.7.0/lib/jsonapi/acts_as_resource_controller.rb#L94
    def resource_klass_name
      @resource_klass_name ||= "#{self.class.name.underscore.sub(/\/serializers/, "").
        sub(/_serializer$/, "")}_resource".camelize.
        sub("Api::", "Api::Jsonapi::")
    end
  end
end

This would then allow me to do stuff like this, to get the actual JSON:

Api::Serializers::User.new(current_user, { current_user: current_user }).json.to_json

Thanks!
Kevin Trowbridge

@chtrinh
Copy link

chtrinh commented Jan 17, 2020

Any suggestions here? Again docs don't line up and my google-fu is failing me. 😞

@chtrinh
Copy link

chtrinh commented Jan 17, 2020

Ok I think figured it out from the test cases: https://github.com/cerebris/jsonapi-resources/blob/master/test/unit/serializer/serializer_test.rb#L23-L37

Please forgive my ignorance but this seems way more complicated than the previous version's implementation. Am I missing something here? Feels like slicing up watermelon till we get water...

@CharlieIGG
Copy link

Is this issue completely abandoned?

@francois-ferrandis
Copy link

I am impacted by this as well. I switched to version 0.9.11 so I could use this feature, until this is fixed.

@lynndylanhurley
Copy link

This issue is causing our project tons of problems. We had a bunch of code that followed the pattern described in the docs, which no longer works.

Ideally the code from the docs should continue to work, and show a deprecation message if necessary with instructions on how to migrate.

@e-pavlica
Copy link

e-pavlica commented Jul 14, 2020

I think the docs might just need updating for v0.10+. There's an object_hash method on JSONAPI::ResourceSerializer that takes the resource and a relationship_data hash that does the trick as far as I can tell.

def object_hash(source, relationship_data)

Specifically, when rendering a resource in a non-JSONAPI::ActsAsResource controller:

def show
  post = Post.find(params[:id])
  
  # ... business logic ...
  resource = PostResource.new(post, { :current_user => current_user })
  json = JSONAPI::ResourceSerializer.new(PostResource).object_hash(post, { :comments => post.approved_comments })
  render :json => { :data => json }
end

NOTE: The above isn't setting the Content-Type header appropriately; it should be set to application/vnd.api+json to conform to the JSONAPI spec.

@SeriouslyAwesome
Copy link

Bumped into this issue today trying to upgrade from 0.9.6. Any updates here?

@ahmadabdelhalim
Copy link

I'm having the same issue.

@jamesdixon
Copy link

@lgebhardt can you provide any insight on this?

@tobias-grasse
Copy link
Contributor

@jamesdixon et al: I asked on the Gitter channel, here's his reply.

Thank you @lgebhardt for maintaining this library, and please ping me if I can help test things for this use-case in v0.11!

@jamesdixon
Copy link

@tobias-grasse thank you!

@bf4
Copy link
Collaborator

bf4 commented Dec 11, 2020

hoisting the answer from gitter here for convenience

 Larry Gebhardt @lgebhardt Oct 27 11:06
Yes, v0.10 has made just serializing a resource a difficult task. I just wasn't aware of how many people were using the library that way. Restoring this functionality for v0.11 is a priority

speaking for myself, we had a test that was like

      context = { current_user: user }	
      resource_class = V1::JobResource	
      resource_options = {	
        include:  ["job_template",],	
        meta: { "job" => "current_user_can_actions" },	
      }	
      serializer = JSONAPI::ResourceSerializer.new(resource_class, resource_options)	
      resource_instance = resource_class.new(model, context)	
      as_json = serializer.serialize_to_hash(resource_instance)	

@Lifehack043
Copy link

Lifehack043 commented Jun 3, 2021

Temporary can use this

def jsonapi_serialize(ids)
 serializer = JSONAPI::ResourceSerializer.new(resource_klass)
 resource_set = get_resource_set(ids)
 resource_set.populate!(serializer, context, {})
 if ids.is_a?(Array)
    serializer.serialize_resource_set_to_hash_plural(resource_set)
  else
    serializer.serialize_resource_set_to_hash_single(resource_set)
  end
end

def get_resource_set(ids)
 id_tree = JSONAPI::PrimaryResourceIdTree.new
 directives = JSONAPI::IncludeDirectives.new(resource_klass, ['']).include_directives
 Array(ids).each do |id|
   identity = JSONAPI::ResourceIdentity.new(resource_klass, id)
   fragment = JSONAPI::ResourceFragment.new(identity)
    id_tree.add_resource_fragment(fragment, directives[:include_related])
  end
  JSONAPI::ResourceSet.new(id_tree)
end

@JohnnyHandy
Copy link

JohnnyHandy commented Aug 9, 2021

@Lifehack043 this is working for me so far on v0.10.5

@xhocquet
Copy link

xhocquet commented Oct 5, 2021

On 0.10.5, I tried using @bf4's solution but had to make a small change to finally get it working -

    resource_class = API::V1::DocumentJobResource
    serializer = JSONAPI::ResourceSerializer.new(resource_class, {})
    resource_instance = resource_class.new(document_job, {})
    serializer.object_hash(resource_instance, {})

This is all without additional metadata/context being passed. See the prior comment for details on that

@bf4
Copy link
Collaborator

bf4 commented Mar 10, 2022

Master has unrelated code which adds serialize_to_hash #1348

@andreasgebhard7
Copy link

andreasgebhard7 commented Aug 17, 2022

For me the comment by @xicreative worked perfectly fine on 0.10.7. I just replaced serialize_to_hash by object_hash and everything worked fine. Thanks a lot @xicreative !!!

@dpep
Copy link

dpep commented Apr 18, 2023

as @bf4 mentioned, it looks like the solution is in place and we just need it shipped. how can we get the next gem version published?

@tilo
Copy link

tilo commented Apr 22, 2023

@lgebhardt @dgeb @HeatherGebhardt @senid231 can this fix be applied to the 0.10.x branch?
This issues is preventing people to use 0.10.x

@mauricio-molina
Copy link

we're also being affected by this - hoping as mentioned above the fix can be applied to the 0.10.x branch

@josephfrazier
Copy link

same here, it'd be helpful to have a 0.10.x release with the fix in place

@Talha345
Copy link

Hi, is there any update on this? Currently, using 0.10.7

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