【发布时间】:2016-12-19 01:28:07
【问题描述】:
是否可以将具有关联的数据转换为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,可以包含与此的关联:
respond_to do |format|
format.json { render json: country.as_json(include: :citizens) }
end
有没有办法把习惯也包括在内?是否可以与国家、其公民和公民的习惯有一个json?
【问题讨论】:
标签: ruby-on-rails json