Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11424 (new defect)

Opened 5 months ago

[PATCH] Invalid SQL from construct_finder_sql_for_association_limiting with nested tables

Reported by: danger Assigned to: core
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: major Keywords: patch
Cc:

Description

When construct_finder_sql_for_association_limiting is generating its optimized query to find ids it only joins the minimum number of tables. It uses all tables required from options[:conditions] and options[:order] and discards the rest. This works most of the time but throws a big error when the conditions aren't in a table immediately adjacent to the model.

# this works fine (and the optimizing query leaves off the `comments` table):

Author.find(:all, :include=>{:posts=>:comments}, :conditions => "posts.type ='SpecialPost'", :limit => 10)
# optimizing SQL generated:
"SELECT DISTINCT `authors`.id FROM `authors` LEFT OUTER JOIN `posts` ON posts.author_id = authors.id WHERE (posts.type ='SpecialPost')  LIMIT 10"

# But this breaks:
Author.find(:all, :include=>{:posts=>:comments}, :conditions => "comments.type = 'Comment'", :limit => 10)
"ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'posts.id' in 'on clause': SELECT DISTINCT `authors`.id FROM `authors` LEFT OUTER JOIN `comments` ON comments.post_id = posts.id WHERE (comments.type = 'Comment')  LIMIT 10"

The easy solution would be to not throw away any tables in the optimizing query. A more difficult solution might be to include only the tables between the model and the tables used in :conditions and :order.

Easy solution attached.

Attachments

generate_valid_sql_on_deeply_nested_tables_and_association_limiting.diff (1.6 kB) - added by danger on 03/25/08 20:03:37.

Change History

03/25/08 20:03:37 changed by danger

  • attachment generate_valid_sql_on_deeply_nested_tables_and_association_limiting.diff added.