Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: include related object in JSON output

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

clip from my notes controller

class NotesController < ApplicationController
  before_filter :authenticate_user!
  respond_to :html, :xml, :json

  # GET /notes
  # GET /notes.xml
  def index
    @notes = Note.includes(:user).order("created_at DESC")
    respond_with @notes
  end

When I ask for the index in json results for example /notes.json, it returns the notes but only returns user_id for the user object. I would like it to also include user.username (and would be curious how to have the whole user object embedded).

Bonus question: I could not find a way to make the column show as author_id and have it relate back to user. If this is easy to do, how do you do it?

like image 260
Codezy Avatar asked Jan 03 '11 04:01

Codezy


2 Answers

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
like image 81
Jimmy Avatar answered Nov 06 '22 10:11

Jimmy


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
like image 28
arthur bryant Avatar answered Nov 06 '22 12:11

arthur bryant