to_json中的Mongoid虚拟属性 [英] Mongoid virtual attributes in to_json

查看:64
本文介绍了to_json中的Mongoid虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一些虚拟(非持久)属性以显示在某些Mongoid模型的JSON表示中,但似乎无法使其起作用:

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没有出现在json中.我在做什么错了?

virtual_attribute doesn't appear in the json. What am I doing wrong?

Edit -好的,所以我想我的实际问题是我无法弄清楚如何对嵌套在根对象中的每个对象数组调用virtual_attribute方法

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.

推荐答案

to_json将选项直接传递给数组和对象. :include只是一个Mongoid东西:

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)

这篇关于to_json中的Mongoid虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆