2013-12-16 132 views
5

我需要呈現爲Json一個複雜的結構。我有一個結構的工作:Rails 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:

雖然it's不工作,我有我的端口屬性。

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都是船屬性。

這是模型對象:

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

你可以包括你嘗試過爲了添加具有嵌套屬性的端口嗎? 另外,你周圍Port的關係是什麼樣的? –

+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

你可能會希望顯示JSON一個更強大的系統。內置的Rails助手的設計主要是爲了簡單的添加,使用戶能夠完成他們想要完成的大部分任務。然而,就你的情況而言,你正在努力讓它做的更多。

我強烈建議您創建一個view object或使用像RABL這樣的寶石。

我的首選是將Rabl用於複雜的JSON。它基本上爲你創建'視圖對象',方法是構建一個特定於領域的語言,這使得在rails中構建複雜的JSON對象變得相對容易。

RABL基本上允許您構建格式爲JSON而不是HTML的視圖。 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