ActiveRecord虚拟属性作为记录属性处理

我遇到问题,to_json没有渲染我的虚拟属性

class Location < ActiveRecord::Base belongs_to :event before_create :generate_oid validates_associated :event attr_accessor :event_oid def event_oid @event_oid = event.oid end end 

event_oid不是返回的数组的一部分:

 Location.first.attributes

当使用to_json自动将记录属性序列化为jason时,这对我来说尤其成问题。 to_json省略了我的虚拟属性。

如何将虚拟属性视为实际实例属性?

编辑:

to_json只是将我的虚拟属性视为实际属性的方法的一个示例。

您想要修改属性哈希。 这里有一些额外的代码可以确保您关心的属性可以与to_json或其他依赖于对象加载属性的方法一起使用。

 class Location < ActiveRecord::Base belongs_to :event before_create :generate_oid validates_associated :event after_save :event_oid attr_accessor :event_oid def event_oid @event_oid = @attributes["event_oid"] = event.oid if event.nil? end def after_initialize event_oid end end 

to_json和许多基于对象属性生成事物列表的其他方法。 在使用数据库表和名称进行对象初始化时会填充哪个,遗憾的是实例变量不会更新此哈希。

PS如果你想以这种方式使用许多属性,这不是很干。 您可以使用符号数组,确定性方法名称和class_eval块一次将此过程应用于多个符号。

警告

我们在这里弄乱了rails内部。 没有人知道它会如何导致其他事情失败。 我还没有测试过save和to_json,当属性hash包含不是列名的键时,两者都有效。 因此使用它需要您自担风险。

怎么样to_json(:methods => [:event_oid]) ,这to_json(:methods => [:event_oid])吗?

然后自己实现#to_json:

 class Location < ActiveRecord::Base def to_json(options={}) options[:methods] ||= [] options[:methods] << :event_oid super(options) end end 

我尝试了FrançoisBeausoleil的答案,并在将to_json修改为as_json之后将其to_json as_json

 def as_json(options={}) options[:methods] ||= [] options[:methods] << :class_to_s super(options) end 
 location.to_json(:methods => :event_oid) 

如下所述: http : //apidock.com/rails/ActiveRecord/Serialization/to_json

在控制器中只需使用:

 format.json { render json: @location.to_json(:methods => :event_oid) }