开发者

Two different JSON views with Rails

Consider the following, I have a Job class that has inputs and one output. I have the following in my开发者_运维知识库 job.rb

  def as_json(options={})
    super(include: [:inputs,:output])
  end

So this has been working very well and my JobController has been dolling out well formatted and useful JSON responses.

I am working on a way to display a version of the Job JSON to the user that only showed the inputs, so I did the following and got some weird behavior:

@job.to_json(include: [:inputs])

This method ignores the options passed to it, and calls the as_json method on the model

So my question is, once you have defined as_json, how do you get a different json view of the object?

Thanks!


You could try this to pass output and inputs by default :

def as_json( options = { :include => {:inputs, :output} } )
   super(options)
end

then you can pass your options for special cases :

@job.as_json( :include => {:inputs} )

More info here : http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜