Rails 4急切加载多个表

时间:2014-03-29 14:30:42

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

我正试图用5个表来加载结果:

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

我正在尝试使用包含(:预订),但根据bullet-gem,急切加载不起作用。在我的观点中,我称之为:

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

我正在获得多行52行代码,这显然意味着我并不急于加载任何数据:

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]

我应该做些什么?

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

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

另外,你是如何在@year中传球的?

答案 1 :(得分:0)

Meeting.includes(:bookings).where(year: @year).references(:bookings)
如果您使用rails 4,

将起作用。