ActiveRecord从DB返回嵌套的JSON数据

时间:2017-08-10 10:39:57

标签: ruby-on-rails ruby activerecord relational-database

我在Postgres有4个数据库表。 courseactivitylessontask

目前,当我在我的控制器中执行Course.find_by_id(params[:id])时,模型会设置为返回课程中的所有课程,但我希望此嵌套扩展到{{1}中的activities并且还包括lessontask的一对一关系。

activity

我的JSON输出目前看起来像这样:

class Course < ActiveRecord::Base
  validates :title, uniqueness: { case_sensitive: false }, presence: true

  has_many :lessons, -> { order(position: :asc) }, dependent: :restrict_with_error
  belongs_to :subject

  accepts_nested_attributes_for :lessons
end


class Lesson < ActiveRecord::Base
  validates :title, uniqueness: { case_sensitive: false }, presence: true
  validates :position, uniqueness: { scope: :course_id }, presence: true

  belongs_to :course
  has_many :activities, dependent: :restrict_with_error
  acts_as_list column: :position, scope: :course

  accepts_nested_attributes_for :course
end


class Activity < ActiveRecord::Base
  validates :name, uniqueness: { case_sensitive: false }, presence: true
  validates :task, presence: true
  validates :term, presence: true

  belongs_to :lesson
  belongs_to :term
  has_one :task, dependent: :destroy

  accepts_nested_attributes_for :task, allow_destroy: true

  attr_accessor :taskable_attributes
end

class Task < ActiveRecord::Base
  validates :name, uniqueness: { case_sensitive: false }, presence: true
  validates :taskable, presence: true

  belongs_to :activity
  belongs_to :taskable, polymorphic: true, dependent: :destroy

  accepts_nested_attributes_for :taskable, allow_destroy: true
end

但我希望它包含更多嵌套数据

{
    "id": 1,
    "title": "Algebra",
    "description": "Do you know your y times table?",
    "subject_id": 1,
    "lessons": [
        {
            "id": 1,
            "title": "Functions",
            "description": "A mapping of inputs to outputs",
            "position": 2,
            "course_id": 1
        }
    ]
}

我以前从未在轨道上使用ruby或ruby,但能够将此嵌套添加到前端应用程序,直到我们的rails开发人员返回将使我的工作变得更容易。

1 个答案:

答案 0 :(得分:1)

您可以在负责的控制器中尝试类似:

render json: @course.to_json( { include: [ lessons: { include: { :task } } ] } )

您还可以排除与only的任何关联中的字段,也可以包含methods:{}的某些方法

干杯