as_json只适用于某些属性

时间:2014-07-16 02:30:23

标签: ruby-on-rails json ruby-on-rails-3

似乎as_json正在为我的一些属性工作,但不是全部。有人能告诉我这里有什么看错了吗?它是"类型"属性不起作用。

def as_json(options = {})
  {
    id: self.id, 
    type: self.type,
    name: self.name 
    }
  end

 def index
    @streams = @current_user.streams
    respond_to do |format|
      format.html { render :index }
      format.json { render :json => @streams.as_json }
    end    
  end

1 个答案:

答案 0 :(得分:0)

此实施存在一些问题。最重要的是,#as_json被错误地覆盖,这意味着没有任何内容通过默认的ActiveModel::Serializers::JSON#as_json方法运行。您可能希望阅读此处的详细文档:http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

假设所有这些值都只是对象的属性,您希望#as_json方法看起来像:

def as_json(opts = {})
  super(opts.merge(only: [:id, :type, :name]))
end

如果它们中的任何一种是方法,而不仅仅是属性,则需要单独包含它们。

一个小问题是,使用render json: @streams将对象渲染为JSON时,您无需手动调用#as_json。这是作为渲染的一部分自动完成的,不需要担心。