ActiveRecord的虚拟属性交合为创纪录的属性 [英] ActiveRecord Virtual Attributes treaded as a record attributes

查看:125
本文介绍了ActiveRecord的虚拟属性交合为创纪录的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与to_json不会呈现我的虚拟属性的问题

I am running into a problem with to_json not rendering my virtual attributes

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不是由返回的数组的一部分:

event_oid is not part of the array returned by:


Location.first.attributes

这是特别的一个问题,我使用to_json自动记录序列化属性,贾森时。 to_json忽略我的虚拟属性。

This is particularly a problem for me when using to_json that automatically serializes record attributes to jason. to_json omits my virtual attribute.

你怎么能当作一个实际实例的虚拟属性的属性?

How can you make a virtual attribute treated as an actual instance attribute?

to_json在这里有我的虚拟属性视为实际的属性将是很好的方法只是一个例子。

to_json is just an example of a method where having my virtual attribute treated as an actual attribute would be nice.

推荐答案

您要修改的属性的哈希值。有一点点额外的code在这里,以确保你所关心的是准备与to_json或取决于属性的对象负载的另一种方法使用的属性。

You want to modify the attributes hash. There's a little extra code here to ensure the attributes you care about are ready to be used with to_json or another method that depends on attributes on object load.

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和大量的产生的基础上的对象的属性的事情列表的其他方法。其中填充的对象初始化与数据库中的表和名称,遗憾的是实例变量不更新该散列。

to_json and a lot of other methods that generate lists of things based on an objects attributes. Which is populated on object initialization with database tables and names, unfortunately instance variables do not update this hash.

P.S。这是不是很干,如果你有一些你想以这种方式使用属性。你可以使用符号,确定性的方法名和class_eval块的阵列应用此过程中多个符号一次。

P.S. this isn't very DRY if you have a number of attributes you want to use in this manner. You could use an Array of symbols, deterministic method names and a class_eval block to apply this process to multiple symbols at once.

我们正在搞乱这里导轨内部。有没有告诉它如何可能会导致其他的事情要失败。我没有测试过超过保存和to_json,这两个工作,当属性哈希包含不是也列名键。所以使用它需要您自担风险。

We're messing with rails internals here. There's no telling how it could cause other things to fail. I haven't tested more than save and to_json, both of which work when the attribute hash contains keys that are not also column names. So use it at your own risk.

这篇关于ActiveRecord的虚拟属性交合为创纪录的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆