Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Preloading associations generates invalid sql for STI and has_many :through when condition added

#5131
class Role < ActiveRecord::Base
  has_many :user_roles
  has_many :users, :through => :user_roles
end

class User < BusinessObject # STI
  has_many :user_roles
  has_many :roles, :through => :user_roles
end

Role.includes(:user_roles => :user).where(:user_roles => {:role_id => '1'}).find("short name")
=> ... ON "business_objects"."id" = "user_roles"."user_id" AND "business_objects"."type" = 'User' ...

and this sql is ok however

Role.includes(:users).where(:user_roles => {:role_id => '1'}).find("short name")
=> ... ON "business_objects"."type" = 'User' ...

The most important part of the sql gets lost in the second query : ON "business_objects"."id" = "user_roles"."user_id"

This leads to totally wrong results preloaded.
where(...) in this example might not have too much sense but it is just to show simple case when such error occurs.
Preloading behaves different when there are conditions for preloaded associations.

Reported by Robert Pankowecki · July 16th, 2010 @ 07:14 AM

State: resolved
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Jon Leighton
    Jon Leighton
    • State changed from new to resolved
    • Importance changed from to Low

    This is no longer an issue. It's covered by test_find_with_sti_join in inner_join_associations_test.rb. (FYI, doing Foo.includes(:bar).where(:conditions) generates the query in the same way as Foo.joins(:bar), except that the former uses LEFT JOIN and the latter uses INNER JOIN.)

    December 21st, 2010 @ 11:25 AM