2

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!

Sergey Potapov
  • 3,819
  • 3
  • 27
  • 46
  • 2
    Does setting an [alias](http://apidock.com/rails/Module/alias_attribute) for the attribute work? Then if you specify `attribute :username` in JR it should pull the value from `:login`. – Alexander Jan 07 '16 at 16:07
  • @Alexander Can you put your answer to the answers? It works, and seems to be the best option among other aliases, because it also works nice with search. – Sergey Potapov Jan 07 '16 at 16:45
  • Sure! Glad to know it worked. – Alexander Jan 07 '16 at 18:03

3 Answers3

2

I think you need to use alias or alias_method. http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
2

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.

Alexander
  • 3,959
  • 2
  • 31
  • 58
  • Thanks! That is not 100% pure solutation (the most preferable would be to not touch the model, only resource), but still it works the best among othe alias options, because it does not breaking filtering (search) feature. Thanks! – Sergey Potapov Jan 08 '16 at 10:57
1

Generally, the easiest way to change attribute name or value is to re-define the attribute. In your case it would be:

attributes :username

def username
  @model.login
end

Here it is in the Readme: https://github.com/cerebris/jsonapi-resources#formatting

Sergii Mostovyi
  • 1,361
  • 1
  • 15
  • 19