缩短respond_with(:include => xxx)

时间:2011-08-05 01:06:20

标签: ruby-on-rails ruby include arel respond-with

我正在寻找一种方法来缩短:include => :response_with中的child生成json。

这是一个例子,不确定它是否可行,但我想知道。

在控制器中:

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

基本上,我正在尝试干掉我的代码...我不想一遍又一遍地输入包含哈希...是否只能在一次调用中包含所有子对象?< / p>

1 个答案:

答案 0 :(得分:5)

ActiveRecord有一个as_json方法,用于定义如何将对象输出为json。默认情况下,您可以使用此方法包含关联的子项,如下所示:

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