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.

.count on a named_scope on a has_many association throws error

#2507

I'm hitting a bug working on an upgrade from Rails 2.2 to 2.3. It occurs in the following case:


class User < ActiveRecord::Base
  has_many :memberships
  has_many :challenges, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :challenge
  belongs_to :user
end

class Challenge < ActiveRecord::Base
  named_scope :blue, :conditions => {:name => 'blue' }
end
# "blue" is just for this test case, made up

The error occurs when calling:


some_user.challenges.blue.count

It tries to generate invalid SQL like this:


SELECT count("challenges".*) AS count_challenges_all FROM "challenges" INNER JOIN "memberships" ON "challenges".id = "memberships".challenge_id WHERE ((("challenges"."name" = 'blue') AND (("memberships".user_id = 1))) AND (("memberships".user_id = 1))) 

The problem as far as I can tell is the "SELECT count("challenges".) part. It works if its is "SELECT count()" or "SELECT count("challenges".id)

(Small note, it also adds the ("memberships".user_id = 1) condition two times, but that's not invalid, it's just excessive, and new in 2.3)

I will start to dive into the source code to see if I can narrow this down a bit.

Reported by Cameron Booth · April 16th, 2009 @ 05:06 AM

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

Activity

  1. Cameron Booth
    Cameron Booth

    I used git bisect to narrow the cause down to this commit:

    http://github.com/rails/rails/co...

    I'll look now at creating a test case, and possibly fixing it if I can figure it out

    April 16th, 2009 @ 05:20 AM

  2. Cameron Booth
  3. Max Lapshin
    Max Lapshin
    • Tag changed from 2.3.2, :through, active_record, sql to 2.3.2, :through, active_record, duplicate, sql

    April 23rd, 2009 @ 10:55 AM

  4. Matt Jones