Finder methods fail when:
(1) there is a :limit, and
(2) there are :includes, and
(3) the conditions clause is a hash, and
(4) the conditions reference the :included association.
For example, the following query fails:
Widget.find :all,
:conditions => {"users.state" => "active", "tags.name" => "fun"},
:include => [:creator, :tags],
:limit => 20
Mysql::Error: Unknown column 'users.state' in 'where clause':
SELECT DISTINCT widgets.id FROM widgets
WHERE (users.state = 'active' AND
tags.name = 'new') LIMIT 20
The problem is in
ActiveRecord::Associations::ClassMethods::conditions_tables,
associations.rb, line 1513ff:
def conditions_tables(options)
# look in both sets of conditions
conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond|
case cond
when nil then all
when Array then all << cond.first
else all << cond
end
end
conditions.join(' ').scan(/([\.a-zA-Z_]+).?\./).flatten
end
The case statement is failing for hashes. It needs an extra
"when" to handle them:
when Hash then all << cond.keys
Here is the patch in context:
def conditions_tables(options)
# look in both sets of conditions
conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond|
case cond
when nil then all
when Array then all << cond.first
when Hash then all << cond.keys # <--- PATCH
else all << cond
end
end
conditions.join(' ').scan(/([\.a-zA-Z_]+).?\./).flatten
end