Rails: include related object in JSON output

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)