Rails 嵌套结构的 as_json 只有第一层工作

birbird · 2013年09月20日 · 最后由 birbird 回复于 2013年09月22日 · 2363 次阅读

我的 Model 有三层,从上到下是 Place,Guide,Story

class Place < ActiveRecord::Base
  has_many :guides, :dependent => :destroy

  def as_json(options={})
    options[:except] ||= [:created_at, :updated_at]
    options[:include] ||= [:guides]

    super(options)
  end
end
class Guide < ActiveRecord::Base
  belongs_to :place
  has_many :stories, :dependent => :destroy

  def as_json(options={})
    options[:except] ||= [:created_at, :updated_at]
    options[:include] ||= [:stories]

    super(options)
  end
end

如果 render :json => @places 的话,只有第一层,即 Place.as_json 生效,Guide.as_json 根本不会被调用。 这咋办啊,知道请指点,谢了先!

谢谢 @vkill,插件还没来得及看。有一个不用插件的方法是这样的,给每个 Model 都显式写个 as_json_options 方法

class Place < ActiveRecord::Base
  has_many :guides, :dependent => :destroy

  def as_json_options
    @options={}
    @options[:except] ||= [:created_at, :updated_at]
    @options[:include] ||= [:guides => Guide.as_json_options]
    return @options
  end

  def as_json(options={})
    super(as_json_options)
  end

end
class Guide < ActiveRecord::Base
  belongs_to :place
  has_many :stories, :dependent => :destroy

  def Guide.as_json_options
    options = {}
    options[:except] ||= [:created_at, :updated_at, :keywords]
    options[:include] ||= [:stories => Story.as_json_options]

    return options
  end

end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号