开发者

include 2nd level in to_json

开发者 https://www.devze.com 2023-02-08 21:59 出处:网络
I\'m using this code to convert a model to json. If i try to use an include 2nd level like this: p = Product.includes({ :variants => { :stocks => :size } }).where(:id => params[:id]).first

I'm using this code to convert a model to json. If i try to use an include 2nd level like this:

p = Product.includes({ :variants => { :stocks => :size } }).where(:id => params[:id]).first
render :json => p.variants.to_json(:include => { :stocks => { :include => :size } })

I receive this error:

undefined method `macro' for nil:NilClass

How I can solve that?开发者_如何学运维


Try this:

render :json => p.variants.map { |v| v.as_json(:include => {:stocks => {:include => :size}}) }

Info about Object#as_json/to_json here.

0

精彩评论

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