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

Sea*_*ary 10 activerecord ruby-on-rails

我遇到了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
Run Code Online (Sandbox Code Playgroud)

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

Location.first.attributes

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

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

编辑:

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

EmF*_*mFi 6

您想要修改属性哈希.这里有一些额外的代码,以确保您关心的属性可以与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
Run Code Online (Sandbox Code Playgroud)

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

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

警告

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