【问题标题】:rails to_json unexpected behavior for include_root_in_jsonrails to_json include_root_in_json 的意外行为
【发布时间】:2011-04-16 01:42:07
【问题描述】:

我有一个这样的模型

class Parent < ActiveRecord::Base
  :has_many :kids
end

class Kid < ActiveRecord::Base
  :has_many :grandkids
  :belongs_to :parent
end

我可以像这样生成json:

the_parent.to_json( :methods => [:kids] )

=> { "parent" : { "kids" : [ { "kid" : { "name" => "kid0" .... 等等。正是我想要的。每个对象看起来像一个带有单个键的散列 - 这是模型名称 - 而值是一个属性散列。太好了。

但是当我尝试序列化整个树时遇到了麻烦,如下所示:

the_parent.to_json( :include => { :kids => { :include => :grandkids } } )

=> { "父母" : { "孩子" : [ { "名字" => "kid0" ... 缺少“孩子”数组中的模型名称。同样的事情发生在孙辈的下一个级别。我将在其他地方解析它,这将有助于确定对象名称(而不是依赖于使用关系名称的约定)。文档宣传这一点:

ActiveRecord::Base.include_root_in_json = true

我发现它没有效果。我的猜测是不同的行为与 :method 和 :include 选项之间的差异有关,但我无法使用 :method 语法来获得我需要的嵌套,我不确定这是否会起作用如果它编译。

有什么想法吗?谢谢,丹

【问题讨论】:

  • 我还应该提到,我正在渲染上下文中调用 to_json:format.json { render :json => the_parent.to_json...
  • 我确信有更好的答案,但作为一种解决方法,我在我的模型中覆盖 to_json 如下: def to_json(args) super( :methods => [:kids] ) end

标签: ruby-on-rails json serialization


【解决方案1】:

作为一种解决方法,我将在我的模型中覆盖 to_json,如下所示:

def to_json(args)
    super( :methods => [:kids] )
end

【讨论】:

  • 这行得通,但如果您要处理大量数据,则会导致性能不佳。 :include 更快!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多