Search code examples
ruby-on-railsrubyjsonapi-resources

How to rename property/attribute of resource with jsonapi-resources ruby gem


I am building json api with rails using jsonapi-resources gem. The library is really great, it does a lot of job.

However some column names in our DB is not really meaninful to be showed in API.

So, my question: is possible to rename property/attribute in resource?

Example:

Let's say I have model User with attribute login.

class User < ActiveRecord::Base
  attr_accessor :login
end

And I want login in API appear as username, e.g.:

class UserResource < JSONAPI::Resource
  attribute :username, map_to: :login
end

Thanks!


Solution

  • Set a :username alias for your :login attribute:

    class User < ActiveRecord::Base
      attr_accessor :login
    
      alias_attribute :username, :login
    end
    

    Then in JSONAPI::Resources (JR) you can specify your username attribute like so:

    class UserResource < JSONAPI::Resource
      attribute :username
    end
    

    By setting an alias, you've mapped the username attribute to the login attribute, so it doesn't matter whether you use username or login, it will return the same value.