1

API 및 클라이언트 응용 프로그램이 있으며 ActiveResource와 함께 레일을 사용하고 있습니다. ActiveResource를 사용할 때 JSON 응답을 평탄하게 만드는 방법은 무엇입니까?

내가의 내가 쓰는 클라이언트 측에 있다고 가정 해 봅시다 ActiveResource::Base

에서 상속 Recruiter 모델을 가지고 :

dave = Recruiter.new(email: "[email protected]", password: "tyu678$--è", full_name:  "David Blaine", company: "GE") 
dave.save 

내가 보내는 요청과 같이 포맷 :

{"recruiter":{ 
    "email": "[email protected]", 
    "password": "tyu678$--è", 
    "full_name": "David Blaine", 
    "company": "GE" 
    } 
} 

및 API에서 얻은 Json 응답은 다음과 같이 형식이 지정됩니다.

{"recruiter":{ 
    "email": "[email protected]", 
    "password": "tyu678$--è", 
    "full_name": "David Blaine", 
    "company": "GE", 
    "foo": "bar" 
    }, 
    "app_token":"ApfXy8YYVtsipFLvJXQ" 
} 

이 문제는 dave.app_token으로 앱 토큰에 액세스 할 수 있지만, 예를 들어 dave.foo을 쓸 수 없기 때문에 오류가 발생합니다.

응답을 병합하거나 재귀 적으로 읽는 방법은 있습니까? API 응답을 그대로 유지하면서 모든 인스턴스의 속성에 액세스 할 수 있습니까?

+0

확인 그것은 일이 링크 http://stackoverflow.com/questions/10712679/flatten-a-nested-json-object – Icicle

답변

0

전체 ActiveResource 과정을 살펴보면 Recruiter 모델에서 load 방법을 덮어 쓸 수 있습니다.

방금 ​​속성을 "평평하게"하는 #HACK 섹션에 코드를 추가했습니다.

def load(attributes, remove_root = false, persisted = false) 
    raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash) 
    @prefix_options, attributes = split_options(attributes) 

    # HACK 
    if !attributes[:app_token].nil? 
    attributes[:recruiter]["app_token"] = attributes[:app_token] 
    attributes = attributes[:recruiter] 
    end 
    # /HACK 

    if attributes.keys.size == 1 
    remove_root = self.class.element_name == attributes.keys.first.to_s 
    end 

    attributes = ActiveResource::Formats.remove_root(attributes) if remove_root 

    attributes.each do |key, value| 
    @attributes[key.to_s] = 
    case value 
    when Array 
     resource = nil 
     value.map do |attrs| 
     if attrs.is_a?(Hash) 
      resource ||= find_or_create_resource_for_collection(key) 
      resource.new(attrs, persisted) 
     else 
      attrs.duplicable? ? attrs.dup : attrs 
     end 
     end 
    when Hash 
     resource = find_or_create_resource_for(key) 
     resource.new(value, persisted) 
    else 
     value.duplicable? ? value.dup : value 
    end 
    end 
    self 
end 
+0

! 감사! – user3778624