使用to_json时如何访问':has_many:through'连接表数据?

时间:2010-08-08 08:37:31

标签: ruby-on-rails json has-many-through model-associations

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

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

2 个答案:

答案 0 :(得分:7)

不确定,但不应该这样做吗?

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

编辑: 这可能也有效,因为childviews属于overvation:

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

答案 1 :(得分: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