我有一个属于用户的笔记类(即一个用户可以创建许多笔记)。
来 self 的笔记 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
当我请求 json 结果中的索引(例如/notes.json)时,它会返回注释,但只返回用户对象的 user_id。我希望它还包含 user.username(并且很好奇如何嵌入整个用户对象)。
额外问题:我找不到让列显示为 author_id 并将其与用户相关联的方法。如果这很容易做到,你是怎么做到的?
最佳答案
我不确定新的 respond_to
/respond_with
样式是否足够灵活以执行此操作。很可能是这样,但据我了解,这只是为了简化最简单的情况。
您可以使用带有 block 的旧式 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
关于ruby-on-rails - rails : include related object in JSON output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4582121/