ActiveRecord 从数据库返回嵌套的 JSON 数据



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

目前,当我在控制器中Course.find_by_id(params[:id])时,模型设置为返回课程中的所有课程,但我希望这种嵌套扩展到lesson中的activities,并包括taskactivity的一对一关系。

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

我的 JSON 输出当前如下所示:

{
"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
}
]
}

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

{
"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,
"activities": [
{
"id": 1,
"title": "Activity 1"
"task": 
{
"id": 1,
"name": "Task name here"
}
}
]
}
]
}

我以前从未使用过 ruby 或 ruby on rails,但是能够在我们的 rails 开发人员返回之前将此嵌套添加到前端应用程序中会让我的工作变得容易得多。

您可以在负责的控制器中尝试如下操作:

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

您还可以从与only的任何关联中排除字段,也可以包含一些带有methods:{}

的方法干杯

最新更新