2013-12-16 3 views
5

복잡한 구조로 Json으로 렌더링해야합니다. 나는 다음 구조 작업이 있습니다레일 4는 json 중첩 된 객체를 렌더링합니다.

render :json => @booking, :include => [:paypal, 
             :boat_people, 
             :boat => {:only => :boat_model, :include => {:boat_model => {:only => :name, :include => { :boat_type => {:only => :name}}}}}] 

하지만 몇 가지 다른 중첩 된 속성을 가지는 포트 속성을 추가 할 미안 수 없습니다 : 같은 보트, (같은 수준) boat_model.

는 UPDATE :

키우면가 작동하지 않지만, 내 포트 속성을 포함한다.

render :json => @booking, :include => [:paypal, 
             :boat_people, 
             :boat => {:only => [:boat_model => {:include => {:boat_model => {:only => :name, :include => { :boat_type => {:only => :name}}}}}, 
                  :port => {:include => :city => {:only => name}}]}] 

즉, boat_model과 port는 모두 보트 속성입니다. 당신은 아마 JSON을 표시하기위한 훨씬 더 강력한 시스템을 원하는거야

class Boat < ActiveRecord::Base 

    attr_accessor :price 
    @price 

    attr_accessor :extrasPrice 
    @extrasPrice 

    def as_json(options = { }) 
    h = super(options) 
    h[:price] = @price  
    h[:extrasPrice] = @extrasPrice 
    h 
    end 


    belongs_to :boat_model 
    belongs_to :port 
    belongs_to :state 
    has_many :photos 
end 
+0

포트를 중첩 속성과 함께 추가하기 위해 시도한 것을 포함 할 수 있습니까? 또한 포트를 둘러싼 관계는 어떻게 생겼습니까? –

+0

@Joe Edgar가 업데이트를 참조하십시오. – Rober

답변

19

나는 그것을 얻었습니다.

render :json => @booking, :include => [:paypal, 
             :boat_people, 
             :boat => {:only => :name, :include => {:port => {:only => :name, :include => {:city => {:only => :name, :include => {:country => {:only => :name}}}}}, 
               :boat_model => {:only => :name, :include => {:boat_type => {:only => :name}}}}}] 
3

:

는 모델 객체입니다. 빌트인 Rails 헬퍼는 사용자가 원하는 것을 대부분 할 수있게 해주는 단순한 추가 기능을 위해 주로 설계되었습니다. 그러나, 당신의 경우에, 당신은 그것을 위해 설계된 것보다 더 많은 것을 만들려고 노력하고 있습니다.

나는 view object을 만들거나 RABL과 같은 보석을 사용하는 것이 좋습니다.

내가 선호하는 것은 복잡한 JSON에 Rabl을 사용하는 것입니다. 기본적으로 복잡한 JSON 객체를 레일에 쉽게 구현할 수있는 도메인 전용 언어를 작성하여 '뷰 객체'를 만듭니다.

기본적으로 RABL을 사용하면 HTML 대신 JSON 형식의보기를 작성할 수 있습니다. DSL은 매우 풍부하며 원하는 모든 것을 할 수 있습니다. 귀하의 경우 코드는 다음과 같이 보일 것입니다 :

app/views/bookings/show.rabl 

object @booking 
#these are attributes that exist on your booking model: 
attributes :booking_attribute, :other_booking_attribute 

child :paypal do 
    #these are attributes that exist on your paypal model: 
    attributes :paypay_attribute1, :other_paypal_attribute 
end 

child :boat_people do 
    #boat_people attributes that you want to include 
    attributes :blah_blah 
end 

child :boat do 
    #boat attributes that you want to include 
    attributes :boat_attribute1, :boat_attribute2 

    child :boat_model do 
    attributes :name 

    child :boat_type do 
     attributes :name 
    end 
    end 

end 
+0

그래서 위의 방법으로는 불가능합니다. – Rober

+0

이것은 정답입니다. rabl은 올바른 방법으로 중첩 된 jsons를 렌더링합니다. – kokemomuke

관련 문제