Rails: include related object in JSON output

后端 未结 3 1228
面向向阳花
面向向阳花 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
    
    0 讨论(0)
  • 2021-02-02 09:42

    I'm not sure the new respond_to/respond_with style is flexible enough to do this. It very well may be, but as far as I understand, it's meant to simplify only the simplest cases.

    You can achieve what you are trying to do with the old-style respond_to with a block, however, by passing parameters to to_json. Try something like this:

    class NotesController < ApplicationController
      def index
        @notes = Note.order("created_at desc")
        respond_to do |format|
          format.json do
            render :json => @notes.to_json(:include => { :user => { :only => :username } })
          end
        end
      end
    end
    
    0 讨论(0)
  • 2021-02-02 09:51

    Would it be possible to do it the other way around?

    def index
      @user = User.includes(:notes).order("created_at DESC")
      respond_with @user
    end
    

    It would be expensive to include user objects each time the @notes is iterated.

    0 讨论(0)
提交回复
热议问题