将has_many结果包含在REST JSON结果中 [英] Include has_many results in REST JSON result

查看:114
本文介绍了将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆