Rails: include related object in JSON output

后端 未结 3 1280
面向向阳花
面向向阳花 2021-02-02 09:20

I have a note class that belongs to a user (ie a user can create many notes).

clip from my notes controller

class NotesController < ApplicationControl         


        
3条回答
  •  我在风中等你
    2021-02-02 09:39

    You can also use Jbuilder(https://github.com/rails/jbuilder) to response with data very flexible.

    @notes = Note.includes(:user).order("created_at DESC")
    

    and in your index.json.jbuilder file, you can

    json.extract! @note
    json.username @note.user.username
    

提交回复
热议问题