Mongoid virtual attributes in to_json

2019-08-28 04:30发布

问题:

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)