Reputation: 99
I am trying to understand ActiveRecord includes. I am trying to retrieve both Folders and Grids in a single query. I have associated Grids and Folders in ActiveAdmin. Why does this query not return Grid associated data? How do I get Folder plus Grid associated data?
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
schema:
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
Upvotes: 0
Views: 156
Reputation: 25029
You are actually retrieving all of the Grid data. If you were to check any of the folders for their grids, they would all be there without executing any more SQL queries.
The point of using includes
is to eager load associations, avoiding the n+1 queries problem.
A good write up on eager loading, and why n+1s are bad, is here:
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Upvotes: 3