Home > Software design >  How to render model associations in JSON respond_to Rails?
How to render model associations in JSON respond_to Rails?

Time:09-23

I have a product model and a kit model through a KitProducts join table.

Product model

has and belongs to many kits

Kit model

has and belongs to many products

How can I get an output of my products with their kit_id in my JSON?

@products = Product.all

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

This will give me only the product itself, I need to be able to show their kit info

Desired JSON output:

products":[{"id":1,"name":"Test", "kit_id": 1}]

I want to be able to do kit.products in my JS file

CodePudding user response:

You can use the include option in your render call:

Example:

render json: @products, include: :kit

This will give you the following output:

[{"id":1,"name":"Test", "kit_id": 1}]

If you want to include more than one association, you can pass an array:

render json: @products, include: [:kit, :other_association]
  • Related