【问题标题】:additional attributes in both JSON and XMLJSON 和 XML 中的附加属性
【发布时间】: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


    【解决方案1】:

    您可以使用include 轻松地将其他嵌套数据添加到 API 响应中。这是一个例子:

    respond_with(@user, :include =&gt; :user_event )

    你还应该在User中添加反向关联:

    has_many :user_events

    您可以将一个数组传递给:include,用于多个模型。它会将它们序列化并适当地嵌套在响应中。

    【讨论】:

    • 我在问题中没有提到的是我想在模型中这样做,因为它必须在几个控制器中考虑到。
    • 没问题!只需在您的模型中覆盖as_json。每次将模型对象序列化为 JSON 时都会调用此方法,因此它将在任何地方使用。 def as_json(options = {}) super options.merge(include: :user_event) end
    猜你喜欢
    • 2011-10-05
    • 2014-01-15
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多