Search code examples
ruby-on-railsincludehas-manyjson-api

Rails with JSON Api - including has_many relationships


I have three models, Item and Transfer and Category (aka Item Type):

class Item < ApplicationRecord
  belongs_to :category
  has_many :transfers
end

class Transfer < ApplicationRecord
  belongs_to :item
end

class Category < ApplicationRecord
  has_many :item
end

In my controller, I have

render json: @item, include: %i[transfer category]
# FWIW the include doesn't seem to affect category at all...

Which results in a JSON Api payload which takes the following shape:

{
  data: {
      id,
      attributes: {
        /* the other attributes */
        transfers: [ { /* full transfer object */ } ]
      },
      relationships: {
        category: { data: { id, type: 'categories' } },
        transfers: { data: [ { /* full transfer object */ } ]
      }
    }
  },
  included: [ { type: 'category', id, attributes } ]
}

The categories are behaving how I expect them to. How do I get it so that each transfer is included in the included array instead of nested in the attributes or in the relationships?

Thank you!

Edit: not a duplicate. I'm not attempting to nest responses, just included them in the included section to be compliant with the JSON API spec. Anyway, I figured it out, and an answer will be forthcoming shortly!


Solution

  • Turns out I was missing a TransferSerializer! Once I added one, it was put in the included array like you'd expect.