我有一個現有的Rails 3應用程序,我添加了一個JSON API。我們有一個Vendor
ActiveRecord模型和一個Employee
ActiveRecord模型。 Employee
屬於Vendor
。在API中,我們希望在JSON序列化中包含Employee
的Vendor
。例如:在Rails JSON序列化中重命名模型關聯屬性?
# 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-y的方式來做我想做的事。有任何想法嗎?
這就是我害怕的...... – thefugal 2010-12-17 01:28:29