3

我有三个模型(在这里简化):

class Child < ActiveRecord::Base
  has_many    :childviews, :dependent => :nullify
  has_many    :observations, :through => :childviews  
end
class Childview < ActiveRecord::Base
  belongs_to  :observation
  belongs_to  :child
end
class Observation < ActiveRecord::Base
  has_many    :childviews, :dependent => :nullify
  has_many    :children, :through => :childviews
end

我正在使用 Rails 的 to_json 方法将其发送到一些 JavaScript,如下所示:

render :layout => false , :json => @child.to_json(
  :include => {
    :observations => {
      :include => :photos, 
      :methods => [:key, :title, :subtitle]
    }
  },
  :except => [:password]
)

这完美地工作。通过连接表(子视图)可以很好地检索观察结果。

但是,我还想获取位于 childviews 连接表中的数据;特别是“needs_edit”的值。

我不知道如何在 to_json 调用中获取这些数据。

谁能帮我?提前谢谢了。

qryss

4

2 回答 2

7

不确定,但这不应该有效吗?

@child.to_json(
  :include => {
    :observations => {
      :include => :photos, 
      :methods => [:key, :title, :subtitle]
    },
    :childviews => { :only => :needs_edit }
  }, 
  :except => [:password]
)

编辑:这也可能有效,因为 childviews belongs_to the overvation:

@child.to_json(
  :include => {
    :observations => {
      :include => { :photos, :childviews => { :only => :needs_edit } } 
      :methods => [:key, :title, :subtitle]
    }
  }, 
  :except => [:password]
)
于 2010-08-08T23:33:23.433 回答
2

感谢 Rock 的指点 - 我现在可以正常工作了!

这段代码:

@child.to_json(:include => 
  {
    :observations => {
      :include => {
        :photos => {},
        :childviews => {:only => :needs_edit}
      }, 
      :methods => [:S3_key, :title, :subtitle]
    }     
  },
  :except => [:password]
)

给我这个输出(为清楚起见缩写):

{
    "child":
    {
        "foo":"bar",
        "observations":
        [
            {
                "foo2":"bar2",
                "photos":
                [
                    {
                        "foo3":"bar3",
                    }
                ],
                "childviews":
                [
                    {
                        "needs_edit":true
                    }
                ]
            }
        ]
    }
}

谢谢你,摇滚!这让我很头疼。

:)

qryss

于 2010-08-09T07:06:39.813 回答