cerebris / jsonapi-resources

A resource-focused Rails library for developing JSON:API compliant servers.
http://jsonapi-resources.com
MIT License
2.32k stars 532 forks source link

Serializer caching / `model_name` bugginess? #952

Closed kevinmtrowbridge closed 7 years ago

kevinmtrowbridge commented 7 years ago

I have a resource, where I have defined the model_name because, it's a namespaced STI model, and the name doesn't quite line up with what I want the resource name to be.

module Api::Jsonapi
  class ProjectNoteResource < OpportunityResource
    model_name 'Opportunity::ProjectNote'
  end
end

When I attempt to use the API to create one of these models, I get the following exception:

Internal Server Error: undefined method `new' for nil:NilClass /gems/jsonapi-resources-0.9.0.beta1/lib/jsonapi/resource.rb:478:in `create_model'

When I looked into it, I see the exception is happening in this method:

module JSONAPI
  class Resource
    class << self
      def _model_class
        return nil if _abstract

        return @model if defined?(@model)
        return nil if self.name.to_s.blank? && _model_name.to_s.blank?
        @model = _model_name.to_s.safe_constantize
        warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." if @model.nil?
        @model
      end
    end
  end
end

Basically the line return @model if defined?(@model) ... it doesn't seem to be behaving correctly. @model is nil ... but defined?(nil) actually returns "local-variable" -- so it's returning nil. This is causing the exception.

The line was changed as a part of PR this commit:

https://github.com/cerebris/jsonapi-resources/commit/827f5db494ff8add581371db2fe6ac7f1c9abded#diff-e6cf31c573bd5f2277b1f16812943df4R986

Where it was changed from the original return @model if @model to return @model if defined?(@model) ...

@DavidMikeSimon was this intentional? Apologies if I am off base? For now, I have monkey patched that line back to the original, and things are working again for me.

Thanks again for the gem! It has taken some investment from me but I am loving it and I believe in the long run this approach is really going to pay off.

kevinmtrowbridge commented 7 years ago

This may be related? https://github.com/cerebris/jsonapi-resources/issues/654

DavidMikeSimon commented 7 years ago

@kevinmtrowbridge I believe you are correct; the change to the line you referenced was a mistake on my part.

@dgeb Thank you for correcting this. :+1: