【发布时间】:2011-07-13 13:18:23
【问题描述】:
我目前正在尝试将属性合并到我的 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 转储中。
This question 建议我可以重写 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”属性。所以看起来我在这里操作的哈希做错了。
【问题讨论】:
标签: ruby-on-rails-3 activerecord xml-serialization jsonserializer