I'm trying to get some virtual (non-persisted) attributes to show up in the JSON representation of some Mongoid models, but can't seem to get it to work:
我试图让一些虚拟(非持久)属性显示在一些Mongoid模型的JSON表示中,但似乎无法让它工作:
class MyModel
include Mongoid::Document
def virtual_attribute
@my_attribute || false
end
def virtual_attribute=(value)
@my_attribute=value
end
end
class MyController
def myaction
false_values=MyModel.where( whatever )
true_values=MyModel.where( something_else ).map{ |model| model.virtual_attribute=true }
@val['my_models']=false_values+true_values
render json: @val.to_json( :include => {:my_models => {:methods => %w(virtual_attribute)}} )
end
end
virtual_attribute
doesn't appear in the json. What am I doing wrong?
virtual_attribute不会出现在json中。我究竟做错了什么?
Edit - ok, so I guess my actual problem is that I can't figure out how to invoke the virtual_attribute
method on each of an array of objects that is nested in the root object.
编辑 - 好吧,所以我想我的实际问题是我无法弄清楚如何在嵌套在根对象中的每个对象数组上调用virtual_attribute方法。
1 个解决方案
#1
0
to_json
passes the options directly to the array and the objects. :include
is only a Mongoid thing:
to_json将选项直接传递给数组和对象。 :include只是一个Mongoid的东西:
render json: @val.to_json(methods: :virtual_attribute)
#1
0
to_json
passes the options directly to the array and the objects. :include
is only a Mongoid thing:
to_json将选项直接传递给数组和对象。 :include只是一个Mongoid的东西:
render json: @val.to_json(methods: :virtual_attribute)