2016-12-18 4 views
0

関連付けを持つデータをjsonに変換することはできますか?Rails、関連付けを持つデータをjsonに変換する方法

のは、我々はこれらのモデルと関連を持っていると仮定しましょう:

class Country < ApplicationRecord 
    has_many :citizens 
    end 

    class Citizen < ApplicationRecord 
    has_many :habits 
    belongs_to :country 
    end 

    class Habit < ApplicationRecord 
    belongs_to :citizen 
    end 

コントローラは次のようになります。

country = Country.find(params[:id]) 

respond_to do |format| 
    format.json { render json: country } 
end 

As already answered in another stackoverflow-question、1はこれで関連付けを含めることができます。

respond_to do |format| 
    format.json { render json: country.as_json(include: :citizens) } 
end 

習慣を含める方法はありますか?国、市民、そして市民の習慣に息をすることは可能でしょうか?

答えて

1

確かに可能です。このコードを試してください:

respond_to do |format| 
    format.json { render json: country.as_json(include: { citizens: { include: :habits }}) } 
end 

詳細については、ドキュメントを参照してください。 Go here

関連する問題