Ruby on rails 3 JSON和XML中的附加属性
我目前正在尝试将属性合并到Rails应用程序的API中。用例很简单。我有一个用户模型:Ruby on rails 3 JSON和XML中的附加属性,ruby-on-rails-3,activerecord,xml-serialization,jsonserializer,Ruby On Rails 3,Activerecord,Xml Serialization,Jsonserializer,我目前正在尝试将属性合并到Rails应用程序的API中。用例很简单。我有一个用户模型: class User < ActiveRecord::Base attr_accessible :email end 这个字符串原来是我的对象的“created_at”属性。因此,看起来我在这里操作的哈希上做错了什么。您可以使用include轻松地将其他嵌套数据添加到API响应中。下面是一个例子: 响应(@user,:include=>:user\u事件) 您还应该在User中添加反向关联: 有很
class User < ActiveRecord::Base
attr_accessible :email
end
这个字符串原来是我的对象的“created_at”属性。因此,看起来我在这里操作的哈希上做错了什么。您可以使用
include
轻松地将其他嵌套数据添加到API响应中。下面是一个例子:
响应(@user,:include=>:user\u事件)
您还应该在User
中添加反向关联:
有很多:用户事件
对于多个型号,您可以将数组传递到
:include
。它将序列化并适当地将它们嵌套在响应中。我在问题中没有提到的是,我希望在模型中这样做,因为它必须在多个控制器中考虑。没问题!只需在您的模型中将重写为_json
。每次将模型对象序列化为JSON时都会调用此方法,因此它将在任何地方使用。def as_json(options={})super options.merge(include::user_event)end
class UserEvent < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
class UserEvent < ActiveRecord::Base
def attributes
@attributes = @attributes.merge "email" => self.email
@attributes
end
end
undefined method `xmlschema' for "2011-07-12 07:20:50.834587":String