Auto eager loading broken for associations that join a column used in an order
jturkel opened this issue · 6 comments
Consider the following models:
class Blog < ActiveRecord::Base
has_many :posts, -> { joins(:author).order('authors.name') }
end
class Post < ActiveRecord::Base
belongs_to :blog
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
end
Auto eager loading (and regular eager loading) is broken for the Blog
post
association:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: authors.name: SELECT "posts".* FROM "posts" WHERE "posts"."blog_id" IN (1) ORDER BY authors.name
Looks like someone has opened a Pull Request to fix this in Rails: rails/rails#11518.
This problem will also affect conditions on joined columns e.g.
class Blog < ActiveRecord::Base
has_many :posts, -> { joins(:author).where('authors.name IS NOT NULL') }
end
Workaround is to specify auto_include = false
on these associations.
Note this only applies to Rails 4.0 and 4.1.
Pushed a change to automatically disable auto eager loading in this case (88c1df3). Leaving this bug open so we can remove this workaround when the underlying issue in the Rails preloader is fixed.
I believe I ran into this problem on Rails 3.2:
has_many :process_flows
has_many :steps, :through => :process_flows, :source => :step,
:select => "steps.*, process_flows.sequence",
:order => "process_flows.sequence"
When goldiloader eager loads this association, the query is invalid (missing the join):
SELECT steps.*, process_flows.sequence
FROM `steps`
WHERE `steps`.`id` IN (1, 3, 4, 2)
# Mysql2::Error: Unknown column 'process_flows.sequence' in 'field list'
I had to specify :auto_include => false
explicitly.
Looks like the Rails issue with eager loading an association with a joins
was fixed in Rails 4.2 via rails/rails#17678. I'm going to remove the workaround for version of Rails >= 4.2. The comment by @dvandersluis for problems eager loading has_many through associations with a order
or select
is being tracked by #18.