Nicholas Haley
Nicholas Haley

Reputation: 4014

How to send HABTM as JSON in Rails API

I am currently working on a recipe app that uses Ember on the frontend and a Rails API on the back. In Rails I have a has and belongs to many relationship between recipes and ingredients. My ingredients model not only stores the ingredient name, but nutritional information so I am not able to simple store ingredients as an array field on recipes.

I am currently confused about how I should set up my Rails API to send properly formatted JSON. According to this

website

Ember expects JSON to be formatted something like this: enter image description here

Assuming this is correct, how should I achieve this in my Rails API?

Upvotes: 4

Views: 470

Answers (2)

prograils
prograils

Reputation: 2376

I use active_model_serializers (0.10.2) and Rails 5:

class RecipeSerializer < ActiveModel::Serializer
  attributes :id, :name, :time, :yield, :servings, :url

  has_many :ingredients # not HABTM here!
end

PUT http://localhost:3000/api/recipes/2 this:

{
  "data": {
    "type": "recipes",
    "attributes": {
      "name": "test",
      "time" : "test2",
      "ingredients_ids": [1]
    }
  }
}

Upvotes: 0

Nicholas Haley
Nicholas Haley

Reputation: 4014

In case anyone has a similar issue, I solved this from my recipe serializer similar to this Stack Overflow Answer

Upvotes: 0

Related Questions