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

birbird · September 20, 2013 · Last by birbird replied at September 22, 2013 · 2364 hits

我的 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
You need to Sign in before reply, if you don't have an account, please Sign up first.