我目前正在尝试将属性合并到我的 Rails 应用程序的 API 中。用例很简单。我有一个用户模型:
class User < ActiveRecord::Base
attr_accessible :email
end
我有另一个模型,基本上将用户链接到一个事件:
class UserEvent < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
我希望能够通过可作为 JSON 或 XML 访问的 API 使用 UserEvent 模型列出与事件相关的所有用户,并且我希望我的 UserEvent 的电子邮件同时出现在 XML 和 JSON 转储中。
这个问题表明我可以重写serialiable_hash,这似乎只适用于JSON,因为看起来to_xml 不使用serializable_hash
我研究的另一种方法是在我的类中覆盖属性方法:
class UserEvent < ActiveRecord::Base
def attributes
@attributes = @attributes.merge "email" => self.email
@attributes
end
end
这适用于 JSON,但在尝试 XML 版本时会引发错误:
undefined method `xmlschema' for "2011-07-12 07:20:50.834587":String
这个字符串原来是我的对象的“created_at”属性。所以看起来我在我在这里操作的哈希上做错了什么。