Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

conditions_tables doesn't understand :condition hashes

#1404

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

Reported by Paul Cantrell · November 18th, 2008 @ 05:21 PM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Paul Cantrell
    Paul Cantrell
    • Tag changed from 2.1, 2.1.2, activerecord, conditions to 2.1, 2.1.2, activerecord, conditions, patch

    Patch attached.

    November 18th, 2008 @ 08:10 PM

  2. Repository
    Repository
    • State changed from new to resolved

    (from [9a4d557713acb0fc8e80f61af18094034aca029a]) Ensure hash conditions on referenced tables are considered when eager loading with limit/offset. [#1404 conditions_tables doesn't understand :condition hashes state:resolved]

    Signed-off-by: Pratik Naik pratiknaik@gmail.com http://github.com/rails/rails/co...

    November 26th, 2008 @ 02:39 PM