Rendering associations in JSON with Rails

Viewed 16

I have 2 models Products and kits, each with a HABTM relationship through a JOIN table KitsProducts

  create_table "kits_products", id: false, force: :cascade do |t|
    t.bigint "product_id", null: false
    t.bigint "kit_id", null: false
  end


      respond_to do |format|
        format.html { render 'new', layout: "builder" }
        format.json do
          render json: [
            products: @kits
          ]
        end
          format.js
      end

I'm rendering a JSON with my kits controller:

@kits = Kit.joins(:products).order(created_at: :asc)

I want the output to include the product_ids associated with that kit (Desired output:)

        "id":1,
        "name":"Kit 1",
        --> I'M MISSING THIS: "product_ids": [1,2,3,4],
        "created_at":"2022-07-03T13:36:46.251Z",
        "updated_at":"2022-07-03T13:37:39.010Z",

I tried with Kit.joins(:products) with no luck.

¿Any ideas?

Thanks!

1 Answers

I finally got it working by using as_json and includes in my respond block:

kits: @kits.as_json(include: :products)
Related