2017-02-14 89 views
1

我有三種模式,並試圖在單個對象中將它們全部輸出爲JSON。是返回多個包含在對象上的Ruby on Rails JSON

的模型和協會如下:

class Customer < ApplicationRecord 
    has_one :subscription 
    has_one :address 
end 

class Address < ApplicationRecord 
    belongs_to :customer 
end 

class Subscription < ApplicationRecord 
    belongs_to :customer 
end 

我嘗試使用下面的返回所有相關的數據作爲JSON:

class HomeController < ApplicationController 
    def index 
    @customers = Customer.all 
    render json: @customers, :include => :address, :subscription 
    end 
end 

但是此函數返回一個語法錯誤的位置紅寶石預計=>某處。任何幫助我如何可以輸出所有這些數據將不勝感激。

回答

1

任何人都在看我剛剛用以下語法回答了這個問題。

class HomeController < ApplicationController 
    def index 
    @customers = Customer.all 
    render json: @customers, :include => [:address, :subscription] 
    end 
end 

地址和訂閱需要在陣列中被傳遞:)