0

I want to set the fields with a value being passed through the URL. For example right now I can do this:

def index
  authors = Author.all
  render json: authors, include: params[:include], fields: {authors: [:id], posts: [:title]}
end

And this works just how I want it to. It comes back with only the author's id and the title of their posts. What I would like to do is something like this:

def index
  authors = Author.all
  render json: authors, include: params[:include], fields: params[:fields]
end

And it would do the same thing as before when I use this URL: http://localhost:3000/authors?include=posts&fields[author]=[id]&fields[posts]=[title] However, when I do that I get all the fields on authors and all the fields on posts.

Here is my serializers for reference:

class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :posts
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :text
  belongs_to :author
  has_many :comments
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Caleb Sayre
  • 401
  • 1
  • 4
  • 12

1 Answers1

0

The "fields" part of the URL will result in Rails params being like this:

{
  "fields" => {
    "author" => "[id]",
    "posts" => "[title]"
  }
}

as you can see there are [] around your attributes, so you need to remove those.

Secondly if you want to be able to be able to request multiple attributes off your Post model, i.e pass title,text in your URL. You'll also need to convert 'title,text' to an array before passing it all to the render method "fields" argument.

(Note: This can change in future versions of Active Model Serializers, since the JsonApi adapter is still under development..)

buren
  • 742
  • 1
  • 8
  • 14