2

我正在寻找一种方法来缩短 :include => :child 内的 respond_with 生成 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)

基本上,我正在尝试干掉我的代码......我不想一遍又一遍地输入包含哈希......有没有办法在一次调用中只包含所有子对象?

4

1 回答 1

5

ActiveRecord has an as_json method that defines how the object should be outputted as json. You can ovveride this method to include the associated children by default so something like this:

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

That should let you clean up your controller a bit, you only need this:

@parent = Parent.find(params[:id])
respond_with @parent
于 2011-08-06T14:04:02.640 回答