1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Fix referencing wrong aliases while joining tables of has many through

association

While joining table of has_many :through association, ActiveRecord will
use the actual table name instead of through-join alias. It results with
a wrong SQL and exception is raised. This only happens when calculation
methods like #count is called.

This issue is affecting Rails 4.1.x and 4.2.x as well.
This commit is contained in:
pinglamb 2015-03-22 16:15:41 +08:00
parent fdf5561965
commit ba057a5ebb
3 changed files with 19 additions and 1 deletions

View file

@ -1,3 +1,10 @@
* Fix referencing wrong table aliases while joining tables of has many through association
(only when calling calculation methods).
Fixes #19276
*pinglamb*
* Reuse the `CollectionAssociation#reader` cache when the foreign key is * Reuse the `CollectionAssociation#reader` cache when the foreign key is
available prior to save. available prior to save.

View file

@ -378,7 +378,7 @@ module ActiveRecord
def construct_relation_for_association_calculations def construct_relation_for_association_calculations
from = arel.froms.first from = arel.froms.first
if Arel::Table === from if Arel::Table === from
apply_join_dependency(self, construct_join_dependency) apply_join_dependency(self, construct_join_dependency(joins_values))
else else
# FIXME: as far as I can tell, `from` will always be an Arel::Table. # FIXME: as far as I can tell, `from` will always be an Arel::Table.
# There are no tests that test this branch, but presumably it's # There are no tests that test this branch, but presumably it's

View file

@ -11,6 +11,10 @@ require 'models/minivan'
require 'models/speedometer' require 'models/speedometer'
require 'models/ship_part' require 'models/ship_part'
require 'models/treasure' require 'models/treasure'
require 'models/developer'
require 'models/comment'
require 'models/rating'
require 'models/post'
class NumericData < ActiveRecord::Base class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data' self.table_name = 'numeric_data'
@ -636,4 +640,11 @@ class CalculationsTest < ActiveRecord::TestCase
Client.update_all(client_of: nil) Client.update_all(client_of: nil)
assert_equal({ nil => Client.count }, Client.group(:firm).count) assert_equal({ nil => Client.count }, Client.group(:firm).count)
end end
def test_should_reference_correct_aliases_while_joining_tables_of_has_many_through_association
assert_nothing_raised ActiveRecord::StatementInvalid do
developer = Developer.create!(name: 'developer')
developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count
end
end
end end