sqlruby-on-railspostgresqlruby-on-rails-4squeel

Changing from joins to includes breaking query


I had this working query:

@search = Availability.joins{facility.activities}
.where{activities.id == s_activity}

But my view was getting a lot of information from Facilities and this resulted in an N+1 issue.

So I decided I should be using includes instead to eager load my associations

@search = Availability.includes{facility.activities}
.where{ facility.activities.id == s_activity)}

But this results in an error:

!! #<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "activities"
LINE 1: ...T "availabilities".* FROM "availabilities" WHERE ("activitie...
                                                             ^

These are the associations:

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

There's a table called activities_facilities for the has_and_belongs_to_many


Solution

  • You need to append .references when using includes with conditions.

    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

    Refer conditions part in includes