Mongoid virtual attributes in to_json

拜拜、爱过 提交于 2019-12-12 03:55:48

问题


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:

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?

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.


回答1:


to_json passes the options directly to the array and the objects. :include is only a Mongoid thing:

render json: @val.to_json(methods: :virtual_attribute)


来源:https://stackoverflow.com/questions/15692872/mongoid-virtual-attributes-in-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!