JSON 和 XML 中的附加属性

发布于 2024-11-23 19:17:25 字数 984 浏览 2 评论 0原文

我目前正在尝试将属性合并到我的 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 似乎没有使用 serialized_hash

我研究的另一种方法是覆盖我的类中的 attribute 方法:

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”属性。所以看起来我在我在这里操作的哈希上做了一些错误的事情。

I am currently trying to incorporate attributes in the API of my Rails app. The use case is simple. I have a User model:

class User < ActiveRecord::Base
  attr_accessible :email
end

I have another model, basically linking the users to an Event:

class UserEvent < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end

I want to be able to list all users related to an event using the UserEvent model through an API accessible as JSON or XML, and I would like the email of my UserEvent to appear in both XML and JSON dump.

This question suggests that I can just override serialiable_hash, well this appears to work only for JSON, as it looks like serializable_hash is not used by to_xml

Another approach I have investigated was to override the attributes method in my class:

class UserEvent < ActiveRecord::Base
   def attributes
    @attributes = @attributes.merge "email" => self.email
    @attributes
  end
end

This works well for JSON, but throws an error when trying the XML version:

undefined method `xmlschema' for "2011-07-12 07:20:50.834587":String

This string turns out to be the "created_at" attribute of my object. So it looks like I am doing something wrong on the hash I am manipulating here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年少掌心 2024-11-30 19:17:25

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

respond_with(@user, :include => :user_event )

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

has_many :user_events

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

You can easily add additional nested data into API responses using include. Here's an example:

respond_with(@user, :include => :user_event )

You should also add the reverse association in User:

has_many :user_events

You can pass in an array to :include for multiple models. It'll serialize and nest them in the response appropriately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文