我有一个现有的 Rails 3 应用程序,我正在向其中添加一个 JSON API。我们有一个 Vendor
ActiveRecord 模型和 Employee
事件记录模型。一个 Employee
属于 Vendor
.在 API 中,我们希望包含一个 Employee
的Vendor
在 JSON 序列化中。例如:
# Employee as JSON, including Vendor
:employee => {
# ... employee attributes ...
:vendor => {
# ... vendor attributes ...
}
}
这很容易。但是,我有一个业务要求,即公共(public) API 不公开内部模型名称。也就是说,对于外界来说,它需要看起来好像
Vendor
模型实际上称为 Business
:# Employee as JSON, including Vendor as Business
:employee => {
# ... employee attributes ...
:business => {
# ... vendor attributes ...
}
}
对于顶级对象,这很容易做到。也就是说,我可以调用
@employee.as_json(:root => :dude_who_works_here)
重命名 Employee
至DudeWhoWorksHere
在 JSON 中。但是对于包含的关联呢?我尝试了一些没有成功的事情:# :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)
我唯一的另一个想法是手动重命名 key ,如下所示:
# 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 的方式来做我想做的事。有任何想法吗?
最佳答案
尝试使用 as_json 的内置选项生成复杂的 JSON 很笨拙。我会覆盖 as_json
在您的模型中,而不必为调用 super
而烦恼一点也不。为 as_json
制作您自己的选项键控制要包含在哈希中的内容。
# employee.rb
def as_json(options = {})
json = {:name => name, ...} # whatever info you want to expose
json[:business] = vendor.as_json(options) if options[:include_vendor]
json
end
关于ruby-on-rails - 在 Rails JSON 序列化中重命名模型关联属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455613/