从联接更改为包含中断查询
Changing from joins to includes breaking query
我有这个工作查询:
@search = Availability.joins{facility.activities}
.where{activities.id == s_activity}
但我的观点是从 Facilities 获取了大量信息,这导致了 N+1 问题。
所以我决定我应该使用 includes
而不是急切加载我的关联
@search = Availability.includes{facility.activities}
.where{ facility.activities.id == s_activity)}
但这会导致错误:
!! #<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "activities"
LINE 1: ...T "availabilities".* FROM "availabilities" WHERE ("activitie...
^
这些是协会:
class Activity < ActiveRecord::Base
has_and_belongs_to_many :facilities
end
class Availability < ActiveRecord::Base
# Associations
belongs_to :facility
end
class Facility < ActiveRecord::Base
# Associations
has_and_belongs_to_many :activities
has_many :availabilities
end
has_and_belongs_to_many
有一个名为 activities_facilities
的 table
在条件.
中使用includes
时需要附加.references
Availability.includes(facility: [:activities]).where('activities.id = ?', s_activity).references(:facility, :activities)
If you want to add conditions to your included models you’ll have to
explicitly reference them
参考条件部分includes
我有这个工作查询:
@search = Availability.joins{facility.activities}
.where{activities.id == s_activity}
但我的观点是从 Facilities 获取了大量信息,这导致了 N+1 问题。
所以我决定我应该使用 includes
而不是急切加载我的关联
@search = Availability.includes{facility.activities}
.where{ facility.activities.id == s_activity)}
但这会导致错误:
!! #<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "activities"
LINE 1: ...T "availabilities".* FROM "availabilities" WHERE ("activitie...
^
这些是协会:
class Activity < ActiveRecord::Base
has_and_belongs_to_many :facilities
end
class Availability < ActiveRecord::Base
# Associations
belongs_to :facility
end
class Facility < ActiveRecord::Base
# Associations
has_and_belongs_to_many :activities
has_many :availabilities
end
has_and_belongs_to_many
activities_facilities
的 table
在条件.
中使用includes
时需要附加.references
Availability.includes(facility: [:activities]).where('activities.id = ?', s_activity).references(:facility, :activities)
If you want to add conditions to your included models you’ll have to explicitly reference them
参考条件部分includes