0
我想弄清楚如何装饰具有属性的特定Mongoid记录,以便to_json
带有包含该属性的回来(请不要告诉我将特定参数传递给to_json
- 这是双重嵌套,这不会在这里工作)。有没有办法做到这一点?所有我能想出的是Ruby/Mongoid用新属性装饰记录
my_record[:my_special_attribute]='foo'
哪个当然不起作用。
我想弄清楚如何装饰具有属性的特定Mongoid记录,以便to_json
带有包含该属性的回来(请不要告诉我将特定参数传递给to_json
- 这是双重嵌套,这不会在这里工作)。有没有办法做到这一点?所有我能想出的是Ruby/Mongoid用新属性装饰记录
my_record[:my_special_attribute]='foo'
哪个当然不起作用。
这里有可能为你工作两个版本:
覆盖to_json
:
require 'mongoid'
Mongoid.load!("mongoid.yml", :development)
class MyClass
include Mongoid::Document
def to_json(options = {})
json = JSON.parse(super)
json['my_special_attribute'] = 'whatever you want'
json.to_json
end
end
p MyClass.new.to_json # => "{\"_id\":\"5155899ee44f7ba6e7000001\",\"my_special_attribute\":\"whatever you want\"}"
参数传递到to_json
(对不起 - 为完整起见):
require 'mongoid'
Mongoid.load!("mongoid.yml", :development)
class MyClass
include Mongoid::Document
def not_a_field
"whatever you want"
end
end
p MyClass.new.to_json(methods: :not_a_field) # => "{\"_id\":\"51558b67e44f7bddb7000001\",\"my_special_attribute\":\"whatever you want\"}"
您甚至可以将此选项传递给嵌套记录(我想这就是你所说的双重嵌套):
my_record.to_json(include: {other_class: {methods: :special_field}})
您也可以将这个方法添加到一个特定的记录(=实例):
my_object = MyClass.new
def my_object.not_a_field
"whatever you want"
end
p my_object.to_json(methods: :not_a_field) # => "{\"_id\":\"51558cc8e44f7bd1f6000001\",\"not_a_field\":\"whatever you want\"}"
只看见自己的[其他问题](HTTP: //stackoverflow.com/questions/15692872/mongoid-virtual-attributes-in-to-json)。首先尝试我的答案。 – 2013-03-29 14:02:48
覆盖'to_json'不起作用,但覆盖'as_json'似乎有诀窍... – cbmanica