This project is archived and is in readonly mode.

#4977 ✓duplicate
Nicholas Clark

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 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.

Comments and changes to this ticket

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>

Referenced by

Pages