Rails: include related object in JSON output

Posted by Codezy on Stack Overflow See other posts from Stack Overflow or by Codezy
Published on 2011-01-03T04:50:10Z Indexed on 2011/01/03 4:53 UTC
Read the original article Hit count: 210

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JSON