【问题标题】:Rails active record eager loading won't load associationsRails 主动记录急切加载不会加载关联
【发布时间】:2013-10-12 21:40:34
【问题描述】:

我正在编写一个 REST api 来返回任务列表。

这是我的一组数据:

id | name         | parent_id
1  | Ride a horse | 0
2  | Eat tacos    | 0
3  | Get some cash| 2

一个任务可以有子任务,所以我让我的模型自我加入:

class Task < ActiveRecord::Base
    belongs_to :parent, :class_name => 'Task', :foreign_key => 'parent_id'
    has_many :children, :class_name => 'Task', :foreign_key => 'parent_id'
end

然后我急切地加载我的任务

def index
    respond_with Task.where(parent_id: 0).includes(:children)
end

控制台显示如下:

任务负载 (0.4ms) SELECT tasks.* FROM tasks WHERE tasks.parent_id = 0

任务负载 (0.3ms) SELECT tasks.* FROM tasks WHERE tasks.parent_id IN (1, 2)

所以它确实会运行查询,但是,它不会将结果放入我的对象中。响应中显示的唯一 2 个任务是 parent_id = 0 的任务。

我做错了吗?我希望这个子任务也出现在响应中。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 eager-loading


    【解决方案1】:

    我认为问题在于默认情况下 to_json 不包含相关对象。 试试这个:

    render json: Task.where(parent_id: 0).includes(:children).to_json(include: :children)
    

    【讨论】:

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