Ich habe eine vorhandene Rails 3-Anwendung, zu der ich eine JSON-API hinzufüge. Wir haben ein ActiveRecord-Modell Vendor
und ein ActiveRecord-Modell Employee
. Ein Employee
gehört zu einem Vendor
. In der API möchten wir eine Employee
Vendor
in der JSON-Serialisierung enthalten. Zum Beispiel:Modellzuordnungsattribute in Rails JSON-Serialisierung umbenennen?
# Employee as JSON, including Vendor
:employee => {
# ... employee attributes ...
:vendor => {
# ... vendor attributes ...
}
}
Das ist einfach genug. Ich habe jedoch eine Geschäftsanforderung, dass die öffentliche API die internen Modellnamen nicht verfügbar macht. Das heißt, mit der Außenwelt, muss es so scheinen, obwohl das Vendor
Modell tatsächlich Business
genannt:
# Employee as JSON, including Vendor as Business
:employee => {
# ... employee attributes ...
:business => {
# ... vendor attributes ...
}
}
Dies ist einfach für das Top-Level-Objekt zu tun. Das heißt, ich könnte @employee.as_json(:root => :dude_who_works_here)
anrufen, um Employee
zu DudeWhoWorksHere
im JSON umzubenennen. Aber was ist mit den eingeschlossenen Verbänden? Ich habe ein paar Dinge ohne Erfolg versucht:
# :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)
Die einzige andere Idee, die ich habe, ist, um manuell den Schlüssel umzubenennen, so etwas wie dieses:
# 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
Aber das scheint unelegant. Ich hoffe, es gibt eine sauberere, mehr Rails-y-Art zu tun, was ich will. Irgendwelche Ideen?
Das war, wovor ich Angst hatte ... – thefugal