0

I'm using rails-api with serializers and I'm especially looking for an easy way to implement "sparse fieldset", that means I want my Rails API to render (json) only the fields I give in the parameter fields:

http://api.website.com/v1/ressource/id?fields=field1,field2

I know we can get field1, field2 etc with params[:field] into the ressource controller, but I'm still not sure: the problem has to be fixed into the controller ? model ? serializer ?

I have seen few posts on this topic and no one is finally given a strong and universal response to this problem. How well-known Rails API are doing this ?

Thank you by advance for your explanations and advice.

Sylvain M
  • 131
  • 1
  • 7

2 Answers2

1

Usually fields are limited in an api response through serializers.

  • approach 1 : if your field values are dynamic In your controller , you can do something like this : say your resource corresponds to Resource

    fieldset = params[:fields].split(',')
    resource_id = params[:id]
    resource = Resource.where(id: resource_id).select([fieldset])
    render json: resource.first
    
  • approach 2 : if you have fixed permutation of fields, you can use different serializers for each combination

    in your controller, instead of accepting fields, accept which serializer you want to use

    resource = Resource.find_by(id: resource_id)
    serializer = params[:serializer]
    render json: resource.first, serializer: serializer: Serializer1 if serializer == 'serializer1'
    
Rohan S
  • 223
  • 1
  • 2
  • 10
0

Using the master branch of ActiveModelSerializers, you can use the fields option of the JsonApi adapter, which does exactly what you expect.

beauby
  • 550
  • 3
  • 11
  • Thanks for your answer, do you know if that branch will be included in rails-api which comes, as announced, with Rails 5 ? – Sylvain M Nov 25 '15 at 10:52