2011-08-05 15 views
2

我正在寻找一种方法来缩短生成json的respond_with内的:include =>:child。缩短response_with(:include => xxx)

下面是一个例子,不知道它是否可能,但我想知道。

在控制器:

@p = Parent.where('id = ?', params[:id]) 
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}}) 

有什么方法对所有包含这些的时候,我定义的实例?

也许是这样的:

@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id]) 
respond_with(@p) 

基本上,我想干涸我的代码...我不希望有继续键入遍地包括散列...有有时候只需要在一次调用中包含所有子对象?

+0

child1,的child2和child3是Parent的组合吗?而grandchild1是child3的组合? – Thilo

+0

是的Thilo,那是对的。孩子们和孙子们会因模特而异,所以我一直在寻找一些可以像帮手一样使用的东西......但是我正在经历一段艰难的时光。 – ThaDick

回答

5

ActiveRecord有一个as_json方法,它定义了如何将对象输出为json。您可以ovveride此方法包括相关的儿童时默认设置是这样的:

class Parent < ActiveRecord::Base 

    # We went to display grandchildren by default in the output JSON 
    def as_json(options={}) 
    super(options.merge(:include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}}) 
    end 


end 

这应该让你清理你的控制器一点,你只需要这样:

@parent = Parent.find(params[:id]) 
respond_with @parent 
+0

嗨马里奥,我不确定重写as_json方法在这里会起作用。我可能会使用任何数量的关联。所以,不知道这会起作用,除非我可以通过选项输入各种子孙,但这与使用原始代码相同,我错了吗? – ThaDick

+0

如果您打算使用不同的选项,那么您需要将它们添加到上面的原始代码之类的声明中。 –

+0

你可能想要'options.reverse_merge'来达到预期的效果。 – sbeam