【发布时间】:2011-05-26 05:33:54
【问题描述】:
我有一个现有的 Rails 3 应用程序,我正在向其中添加一个 JSON API。我们有一个Vendor ActiveRecord 模型和一个Employee ActiveRecord 模型。 Employee 属于 Vendor。在 API 中,我们希望在 JSON 序列化中包含 Employee 的 Vendor。例如:
# Employee as JSON, including Vendor
:employee => {
# ... employee attributes ...
:vendor => {
# ... vendor attributes ...
}
}
这很容易。但是,我有一个业务要求,即公共 API 不公开内部模型名称。也就是说,在外界看来,Vendor 模型实际上需要被称为Business:
# Employee as JSON, including Vendor as Business
:employee => {
# ... employee attributes ...
:business => {
# ... vendor attributes ...
}
}
这对于顶级对象很容易做到。也就是说,我可以调用@employee.as_json(:root => :dude_who_works_here) 将JSON 中的Employee 重命名为DudeWhoWorksHere。但是对于包含的关联呢?我尝试了一些没有成功的事情:
# :as in the association doesn't work
@employee.as_json(:include => {:vendor => {:as => :business}})
# :root in the association doesn't work
@employee.as_json(:include => {:vendor => {:root => :business}})
# Overriding Vendor's as_json doesn't work (at least, not in a association)
# ... (in vendor.rb)
def as_json(options)
super(options.merge({:root => :business}))
end
# ... elsewhere
@employee.as_json(:include => :vendor)
我唯一的另一个想法是手动重命名密钥,如下所示:
# In employee.rb
def as_json(options)
json = super(options)
if json.key?(:vendor)
json[:business] = json[:vendor]
json.delete(:vendor)
end
return json
end
但这似乎不优雅。我希望有一种更清洁、更符合 Rails 的方式来做我想做的事。有什么想法吗?
【问题讨论】:
标签: ruby-on-rails json serialization activerecord ruby-on-rails-3