JSON API를 추가 할 기존 Rails 3 애플리케이션이 있습니다. 우리는 Vendor
ActiveRecord 모델과 Employee
ActiveRecord 모델을 가지고 있습니다. Employee
은 Vendor
에 속합니다. API에서 Employee
의 Vendor
을 JSON 직렬화에 포함하려고합니다. 예 :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에서 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
을하지만 그 우아 보인다. 내가 원하는 것을보다 깨끗하고, 더 레일스 방식으로 사용할 수 있기를 바라고 있습니다. 어떤 아이디어?
그건 제가 두려워했던 것입니다 ... – thefugal