【问题标题】:Rails, how to convert data with association, that has association, to jsonRails,如何将具有关联的数据转换为json
【发布时间】: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


    【解决方案1】:

    是的,这绝对是可能的。试试这个代码:

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

    您可以参考文档了解更多详细信息。 Go here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多