我遇到了 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 省略了我的虚拟属性。
如何将虚拟属性视为实际实例属性?
Edit:
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 和许多其他基于对象属性生成事物列表的方法。它是在对象初始化时使用数据库表和名称填充的,不幸的是实例变量不会更新此哈希。
附:如果您想以这种方式使用许多属性,那么这并不是很干燥。您可以使用符号数组、确定性方法名称和 class_eval 块将此过程一次应用于多个符号。
Warning
我们在这里搞乱了 Rails 的内部结构。没有人知道它如何会导致其他事情失败。除了 save 和 to_json 之外,我还没有测试过更多内容,当属性哈希包含不是列名的键时,这两种方法都可以工作。因此,使用它需要您自担风险。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)