2011-03-31 5 views
8

임베디드 json 객체에서 불필요한 루트 요소에 문제가 있습니다. 여기 는 청소 소스입니다 :ActiveResource 쿼리에서 임베디드 객체의 json 루트 요소 사용 안 함

사용자 모델 :

{ 
    "id":0, 
    "user_name":null, 
    "credit_card": 
    {"number":null} 
} 

컨트롤러의 동작 :

def new 
@user = User.build 
@user.id = nil 
end 

User.build 나에게 다음 JSON을주는 '새로운'

class User < ActiveResource::Base 
     self.format = :json 
     self.element_name = "user" 
     #... 
end 

컨트롤러의 액션 '생성'

def create 
    @user = User.new(params[:user]) 
    @user.save 
end 

보기 '_form.html.erb'

<%= form_for(@user) do |f| %> 
    <%= f.label :user_name %> 
    <%= f.text_field :user_name %> 

     <%= f.fields_for @user.credit_card do |cc_f| %> 
      <%= cc_f.label :number %> 
      <%= cc_f.text_field :number %> 
     <% end %> 
<% end %> 

나는 사용자 응용 프로그램은 다음 JSON을 보내 절약 해요 :

{ 
"user"=> 
    {"credit_card"=> 
    {"credit_card"=> 
     {"number"=>"xxxxyyyyzzzzaaaa"} 
    }, 
    "user_name"=>"test" 
    }, 
"api_client_key"=>"top_secret" 
} 

문제 CREDIT_CARD 키의 중복입니다. 어떻게 해결할 수 있습니까?


최종 솔루션 :

class User < ActiveResource::Base 
     self.include_root_in_json = false 
     self.format = :json 
     self.element_name = "user" 

     def to_json(options = {}) 
      { 
      self.class.element_name => self.attributes 
      }.to_json(options) 
     end 
# ... 
end 

덕분에 당신은 정상 루트를 유지하고 단지 관련된 신용 카드 개체의 뿌리를 제거해야하는 경우

답변

11

ActiveResource::Base.include_root_in_json = false 

을 시도 올리버 반스에 , 다음과 같이 json 출력을 #to_json으로 사용자 정의해야 할 수도 있습니다.

def to_json(options = {}) 
    { "user"=> 
     {"credit_card"=> 
     {"number"=> self.credit_card.number } 
     }, 
     "user_name"=> self.user_name 
    }.to_json(options) 
end 
+1

퀘스트 리온이 ActiveResource 인 경우 ActiveRecord를 사용해야하는 이유는 무엇입니까? – Fivell

+0

ActiveResource는 동일한 매개 변수를가집니다. 하지만 "user"요소도 제거합니다. –

+0

다음 요청이 필요합니다. { "user"=> { "user_name"=> "test", "credit_card"=> { "number"= ""...}}, "api_client_key"= > "top_secret" }' 하지만 난 얻을 '{ "_ 이름"=> "테스트", "CREDIT_CARD"=> { "번호"=> "..."}, "api_client_key"= > "top_secret" }' –