Skip to content

Commit

Permalink
Fixed STI type condition for eager loading of associations
Browse files Browse the repository at this point in the history
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
tarmo committed Aug 24, 2008
1 parent 56dc039 commit fcc5a6e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
6 changes: 2 additions & 4 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -1940,10 +1940,8 @@ def association_join
else
""
end || ''
join << %(AND %s.%s = %s ) % [
connection.quote_table_name(aliased_table_name),
connection.quote_column_name(klass.inheritance_column),
klass.quote_value(klass.sti_name)] unless klass.descends_from_active_record?
join << %(AND %s) % [
klass.send(:type_condition, aliased_table_name)] unless klass.descends_from_active_record?

[through_reflection, reflection].each do |ref|
join << "AND #{interpolate_sql(sanitize_sql(ref.options[:conditions]))} " if ref && ref.options[:conditions]
Expand Down
7 changes: 4 additions & 3 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -1581,10 +1581,11 @@ def add_conditions!(sql, conditions, scope = :auto)
sql << "WHERE #{merged_conditions} " unless merged_conditions.blank?
end

def type_condition
def type_condition(table_alias=nil)
quoted_table_alias = self.connection.quote_table_name(table_alias || table_name)
quoted_inheritance_column = connection.quote_column_name(inheritance_column)
type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{sti_name}' ") do |condition, subclass|
condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{subclass.sti_name}' "
type_condition = subclasses.inject("#{quoted_table_alias}.#{quoted_inheritance_column} = '#{sti_name}' ") do |condition, subclass|
condition << "OR #{quoted_table_alias}.#{quoted_inheritance_column} = '#{subclass.sti_name}' "
end

" (#{type_condition}) "
Expand Down
Expand Up @@ -68,6 +68,18 @@ def test_eager_association_loading_with_has_many_sti
end
end

def test_eager_association_loading_with_has_many_sti_and_subclasses
silly = SillyReply.new(:title => "gaga", :content => "boo-boo", :parent_id => 1)
silly.parent_id = 1
assert silly.save

topics = Topic.find(:all, :include => :replies, :order => 'topics.id, replies_topics.id')
assert_no_queries do
assert_equal 2, topics[0].replies.size
assert_equal 0, topics[1].replies.size
end
end

def test_eager_association_loading_with_belongs_to_sti
replies = Reply.find(:all, :include => :topic, :order => 'topics.id')
assert replies.include?(topics(:second))
Expand Down

0 comments on commit fcc5a6e

Please sign in to comment.