1

我试图弄清楚如何用一个属性装饰一个特定的 Mongoid 记录,以便to_json返回包含该属性(请不要告诉我将特定参数传递给to_json- 这是双重嵌套的,在这里不起作用)。有没有办法做到这一点?我能想到的只有

my_record[:my_special_attribute]='foo'

这当然行不通。

4

1 回答 1

1

以下是两个可能适合您的版本:

覆盖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\"}"
于 2013-03-29T13:12:42.780 回答