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