Rails:在JSON输出中包含相关对象
我有一个属于用户的笔记类(即用户可以创建许多笔记)。
从笔记控制器剪辑
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
当我在json结果中请求索引例如/notes.json时,它返回注释但只返回用户对象的user_id。 我希望它还包括user.username(并且好奇如何嵌入整个用户对象)。
奖金问题:我找不到让列显示为author_id的方法,并将其与用户联系起来。 如果这很容易做到,你怎么做?
我不确定新的respond_to
/ respond_with
风格是否足够灵活。 它很可能是,但据我所知,它只是为了简化最简单的情况。
但是,通过将参数传递给to_json
,您可以实现使用块的旧式respond_to
尝试执行的to_json
。 尝试这样的事情:
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
您还可以使用Jbuilder( https://github.com/rails/jbuilder )来非常灵活地响应数据。
@notes = Note.includes(:user).order("created_at DESC")
在你的index.json.jbuilder文件中,你可以
json.extract! @note json.username @note.user.username
是否有可能以相反的方式做到这一点?
def index @user = User.includes(:notes).order("created_at DESC") respond_with @user end
每次迭代@notes
时包含用户对象都是昂贵的。