Rails 4 ActiveRecord包含

时间:2014-03-15 16:24:17

标签: ruby-on-rails rails-activerecord

我想了解ActiveRecord包含的内容。我试图在一个查询中检索文件夹和网格。我在ActiveAdmin中关联了网格和文件夹。为什么此查询不返回网格关联数据?如何获取文件夹加网格关联数据?

irb(main):002:0> Folder.includes(:grids)
      Folder Load (85.4ms)  SELECT `folders`.* FROM `folders`
      Grid Load (93.1ms)  SELECT `grids`.* FROM `grids` WHERE `grids`.`folder_id` IN (1, 2, 3)
    => #<ActiveRecord::Relation [#<Folder id: 1, name: "Red", created_at: "2014-03-14 06:02:09", updated_at: "2014-03-14 06:03:46">, #<Folder id: 2, name: "Yellow", created_at: "2014-03-14 06:03:33", updated_at: "2014-03-14 06:04:02">, #<Folder id: 3, name: "Blue", created_at: "2014-03-14 06:04:20", updated_at: "2014-03-14 06:04:20">]>

class Grid < ActiveRecord::Base
  belongs_to :folder
  has_many :role_grids
  has_many :roles, :through => :role_grids
end

class Folder < ActiveRecord::Base
  has_many :grids
end

模式:

create_table "folders", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "grids", force: true do |t|
    t.string   "title"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "folder_id"
  end

1 个答案:

答案 0 :(得分:3)

您实际上正在检索所有网格数据。如果你要检查任何文件夹的网格,他们都会在那里不再执行任何SQL查询。

使用includes的重点是热切加载关联,避免了n + 1查询问题。

关于急切加载的好记录,以及为什么n + 1不好,就在这里:

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations