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.

Calling 'size' on an 'has_many :through' association errors

#4977

When trying to call size on an has_many through association, an error is thrown. Expected behavior would follow the vanilla has_many

I have a gist on Github that also tries to explain it.

For the following structure:

class Contact < ActiveRecord::Base
  has_one :family
end

class Family < ActiveRecord::Base
  has_many :contacts
  has_many :members
end

class Member < ActiveRecord::Base
  belongs_to :family
  has_many :contacts, :through => :family
end

When Member.new.contacts.size is called, the following error results:


ActiveRecord::StatementInvalid: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 1: SELECT COUNT(*) AS count_id FROM
contacts INNER JOIN families ON contacts.family_id = families.id WHERE (contacts.type = 'FamilyContact') AND ((families.id = ))

Since this is a new object it shouldn't be querying at all. It also occurs when calling on a saved object (in this example, a saved Member object). Both times it fails to insert the associations through models id.

Reported by Nicholas Clark · June 26th, 2010 @ 12:56 AM

State: duplicate
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Nicholas Clark
    Nicholas Clark
    • Tag changed from hasmany, rails3, size, through to hasmany, has_many, has_many_association, has_many_through, has_many_through_association, rails3, size, through

    June 26th, 2010 @ 02:18 AM

  2. Ryan Bigg
    Ryan Bigg

    I don't get where contacts.type comes into this. Sure you're not doing STI?

    June 26th, 2010 @ 03:12 AM

  3. Andrew White
    Andrew White
    • State changed from new to duplicate
    • Importance changed from to Low

    June 26th, 2010 @ 01:44 PM