JSON包含语法 [英] JSON include syntax

查看:103
本文介绍了JSON包含语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设置:Rails 2.3.10,Ruby 1.8.7

My setup: Rails 2.3.10, Ruby 1.8.7

我在几个模型之间有一组相当复杂的关系.

I have a rather complicated set of relationships between several models.

class A
  has_many :classB
  has_many :classD
end

class B
  belongs_to :classA
  has_many :classC
end

class C
  belongs_to :classB
  belongs_to :classE
end

class D
  belongs_to :classA
  belongs_to :classE
end

class E
  has_many :classD
  has_many :classC
end

我在使用JSON语法获取类A开头的所有相关信息时遇到问题.这是我到目前为止的工作.

I'm having an issue with the JSON syntax to get all the related information starting with classA. Here's what I have working so far.

classA.to_json(:include => {:classB => {:include => [:classC, :classE]}})

我无法使语法同时包含classD和相关的classE记录.

I can't get the syntax working to also include classD and related classE records.

更新实际上,除了我不能混合使用哈希和数组之外,类似的事情可能会起作用

UPDATE Actually something like this might work except that I can't mix hashes and arrays

classA.to_json(:include => [ :classB => { :include => { :classC => { :include => :classE } } },
                             :classD, :classE  ])

请注意,我在上面的示例代码中没有使用单数/复数,但是在我的真实代码中,我使用了单数/复数.任何见解将不胜感激.

Note that I didn't use singular/plural in my example code above but in my real code, I am. Any insights will be much appreciated.

谢谢, 鲍勃

推荐答案

这应该有效:

classA.to_json(:include => {
  :classB => {:include => {:classC => {:include => :classE}}},
  :classD => {},
  :classE => {},
})

这篇关于JSON包含语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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