4

I'm trying to eager load results with 5 tables:

class Meeting < ActiveRecord::Base
  has_many :bookings
end

class Booking < ActiveRecord::Base
  belongs_to :user
  belongs_to :meeting
  belongs_to :role
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :group_memberships
  has_many :users, through: :group_memberships
end

class GroupMembership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :group_memberships
  has_many :groups, through: :group_memberships
end

Inside MeetingController.rb:

def index
    @meetings = Meeting.where(year: @year)
end

I'm trying to use includes(:bookings) but according to bullet-gem the eager loading is not working. And inside my view I'm calling this line:

@meetings.each do |meeting|
  meeting.bookings.find_by(group: @group, role: @role)
end

I'm getting multiple 52 lines of this code which clearly means that I'm not eager loading any data:

Booking Load (0.1ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."meeting_id" = ? AND "bookings"."user_id" = 8 AND "bookings"."group_id" = 2 LIMIT 1  [["meeting_id", 207]]
  Rendered shared/_book.html.haml (1.0ms)
  Booking Load (0.1ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."meeting_id" = ? AND "bookings"."group_id" = 2 AND "bookings"."role_id" = 4 LIMIT 1  [["meeting_id", 208]]
  Booking Load (0.0ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."meeting_id" = ? AND "bookings"."user_id" = 8 AND "bookings"."group_id" = 2 LIMIT 1  [["meeting_id", 208]]
  Rendered shared/_book.html.haml (1.0ms)
  Booking Load (0.1ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."meeting_id" = ? AND "bookings"."group_id" = 2 AND "bookings"."role_id" = 4 LIMIT 1  [["meeting_id", 209]]

bullet.log:

2014-03-29 15:30:48[WARN] user: karlingen
localhost:3000http://localhost:3000/meetings/host
Unused Eager Loading detected
  Meeting => [:bookings]
  Remove from your finder: :include => [:bookings]

Any ideas what I should be doing?

karlingen
  • 13,800
  • 5
  • 43
  • 74

2 Answers2

0

Try the following:

@meetings = Meeting.includes(:bookings).where(year: @year)

Also, how are you passing in the @year?

0
Meeting.includes(:bookings).where(year: @year).references(:bookings)

will work if you are using rails 4.

bummi
  • 27,123
  • 14
  • 62
  • 101
Chitra
  • 1,294
  • 2
  • 13
  • 28