This project is archived and is in readonly mode.

#5131 ✓resolved
Robert Pankowecki

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

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

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

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

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.

Comments and changes to this ticket

  • Jon Leighton

    Jon Leighton December 21st, 2010 @ 11:25 AM

    • 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.)

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>