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

Allow for non id primary keys #261

Open
ychaker opened this issue Jun 26, 2017 · 0 comments
Open

Allow for non id primary keys #261

ychaker opened this issue Jun 26, 2017 · 0 comments

Comments

@ychaker
Copy link

ychaker commented Jun 26, 2017

Hello,
Firstly, thank you for all of your hard work with this gem, it's been great using it.

I ran into an issue when using something other than the id as a primary key. Here's my resource definition:

module Api
  class Metro < ::Api::Base
    self.primary_key = :short_id

    # Overriding this to use the primary key instead of the id field
    #
    # When we represent this resource for serialization (create/update), we do so
    # with this implementation
    #
    # @return [Hash] Representation of this object as JSONAPI object
    def as_json_api(*)
      attributes.slice(:id, :type).tap do |h|
        if :id != self.class.primary_key
          h[:id] = attributes[self.class.primary_key]
        end

        relationships_for_serialization.tap do |r|
          h[:relationships] = self.class.key_formatter.format_keys(r) unless r.empty?
        end
        h[:attributes] = self.class.key_formatter.format_keys(attributes_for_serialization)
      end
    end
  end
end

without overriding as_json_api, the gem was sending the request to the proper url: /metros/:short_id but the payload looked like this: { data: { id: 1, type: 'metros' } } where the id value was the id field instead of the short_id so the id in the data payload did not match the url and the API was returning a 400 response because they identifiers weren't matching.

Overriding the as_json_api method works, but of course it would be better if the support for custom primary keys was baked into the gem.

Thanks.

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

1 participant