将has_many结果包含在REST JSON结果中 [英] Include has_many results in REST JSON result
本文介绍了将has_many结果包含在REST JSON结果中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为List
的模型,该模型为has_many :entries
.像往常一样,Rails 3为List
I have a Model called List
that has_many :entries
. As usual, Rails 3 generated this show method for List
def show
@list = List.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @list }
end
end
如何更改format.json
以将json响应中的entries
结果也包括在json响应中?
How can I change format.json
to include the entries
results from @list
in the json response as well?
我知道我可以将@list
转换为Hash,将.entries
的Hash值添加到该值,然后渲染该Hash,但是我怀疑Rails袖手旁观.
I know I could convert @list
to a Hash, add the Hash value of .entries
to that, then render the Hash, but I suspect that Rails has a more elegant trick up its sleeve.
推荐答案
是的,您可以为to_json
提供一个:include
选项:
Yes, there's an :include
option you can give to to_json
:
format.json { render json: @list.to_json(:include => :entries) }
这篇关于将has_many结果包含在REST JSON结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文