# Possible bug: belongs\_to with :class\_name and eager loading

**URL:** <https://www.ruby-forum.com/t/possible-bug-belongs-to-with-class-name-and-eager-loading/124978>\
**Category:** Rails\
**Created:** [January 4, 2008, 9:24am UTC](https://www.ruby-forum.com/t/possible-bug-belongs-to-with-class-name-and-eager-loading/124978 "2008-01-04T09:24:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/db5fbb/32.png) [@bryan](https://www.ruby-forum.com/u/bryan)\
**Post date:** [January 4, 2008, 9:24am UTC](https://www.ruby-forum.com/t/possible-bug-belongs-to-with-class-name-and-eager-loading/124978/1 "2008-01-04T09:24:24Z")

</div>

In my model:  
class Call \< ActiveRecord::Base  
belongs\_to :doctor, :class\_name =\> ‘User’  
end

In the migration:  
t.column :doctor\_id, :int

call.doctor.last\_name works great. But my view had an N+1 problem.  
So I modified my find to this:

@calls = Call.find(:all, :conditions =\> { :day =\>  
(d-1.day)…d.end\_of\_month }, :include =\> [:doctor])

Suddenly my code blew up with an SQL error. The SQL contained  
`calls`.user\_id instead of `calls`.doctor\_id. I found the fragment of  
code causing the error. In Rails 2.0.2, this is lines 1704-1711 of  
active\_record/associations.rb:

```
          when :belongs_to
              " #{join_type} %s ON %s.%s = %s.%s " % [
                 table_name_and_alias,
     connection.quote_table_name(aliased_table_name),
     reflection.klass.primary_key,

```

connection.quote\_table\_name(parent.aliased\_table\_name),  
options[:foreign\_key] || klass.to\_s.foreign\_key  
]

I worked around this possible bug by changing my model code to:

belongs\_to :doctor, :class\_name =\> ‘User’, :foreign\_key =\>  
‘doctor\_id’

It seems I shouldn’t have to do that. Is this a bug?

thanks,  
Bryan

---

<div class="post-metadata">

**Author:** ![bryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/db5fbb/32.png) [@bryan](https://www.ruby-forum.com/u/bryan)\
**Post date:** [January 4, 2008, 12:27pm UTC](https://www.ruby-forum.com/t/possible-bug-belongs-to-with-class-name-and-eager-loading/124978/2 "2008-01-04T12:27:43Z")

</div>

On 4 Jan 2008, at 08:24, Bryan L. wrote:

> So I modified my find to this:
> 
> @calls = Call.find(:all, :conditions =\> { :day =\>  
> (d-1.day)…d.end\_of\_month }, :include =\> [:doctor])
> 
> Suddenly my code blew up with an SQL error. The SQL contained  
> `calls`.user\_id instead of `calls`.doctor\_id. I found the fragment of  
> code causing the error. In Rails 2.0.2, this is lines 1704-1711 of  
> active\_record/associations.rb:

THis appears relevant: [http://dev.rubyonrails.org/changeset/8456](http://dev.rubyonrails.org/changeset/8456)  
Looks like this was a bug and it has been fixed  
Fred
