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

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)。

然而的,我也想在那个在childviews坐镇数据连接表;专门针对 'needs_edit' 的值。

我无法弄清楚如何在这个数据在to_json电话搞定。

谁能帮助我?提前非常感谢。

qryss

有帮助吗?

解决方案

不知道,但应该不是这个工作?

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

编辑: 这可能工作过,因为childviews belongs_to的的overvation:

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

其他提示

由于岩石的指针 - !我现在有工作

此代码:

@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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top