This project is archived and is in readonly mode.

Calling 'size' on an 'has_many :through' association errors
Reported by Nicholas Clark | June 26th, 2010 @ 12:56 AM
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 FROMfamilies 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.
Comments and changes to this ticket
- 
            
         Nicholas Clark June 26th, 2010 @ 02:18 AM- Tag changed from hasmany, rails3, size, through to hasmany, has_many, has_many_association, has_many_through, has_many_through_association, rails3, size, through
 
- 
         Ryan Bigg June 26th, 2010 @ 03:12 AMI don't get where contacts.type comes into this. Sure you're not doing STI? 
- 
         Andrew White June 26th, 2010 @ 01:44 PM- State changed from new to duplicate
- Importance changed from  to Low
 Duplicate of #4887 
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>
People watching this ticket
Tags
Referenced by
- 
         4887 
          has_many through belongs_to association bug
        Someone else has reported this on #4977.
Definitely need ... 4887 
          has_many through belongs_to association bug
        Someone else has reported this on #4977.
Definitely need ...
 Andrew White
      Andrew White
 Jeremy Kemper
      Jeremy Kemper
 Nicholas Clark
      Nicholas Clark
 Ryan Bigg
      Ryan Bigg