2013-12-16 25 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:

うまくいっていませんが、私は私のポート属性が含まれます。

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

ポートにネストされた属性を追加するために試したことを含めることはできますか? また、ポートを囲む関係はどのように見えますか? –

+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のような宝石を使用することを強くお勧めします。

私の好みは、複雑な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

関連する問題