2013-12-16 88 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