# Strange bug in has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/strange-bug-in-has-and-belongs-to-many/152812>\
**Category:** Rails\
**Created:** [November 7, 2008, 4:59pm UTC](https://www.ruby-forum.com/t/strange-bug-in-has-and-belongs-to-many/152812 "2008-11-07T16:59:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rey9999](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8e8cbc/32.png) [@Rey9999](https://www.ruby-forum.com/u/Rey9999)\
**Post date:** [November 7, 2008, 4:59pm UTC](https://www.ruby-forum.com/t/strange-bug-in-has-and-belongs-to-many/152812/1 "2008-11-07T16:59:14Z")

</div>

Hello everyone.

I have two Classes, linked by a HABTM relationship.

class Building \< ActiveRecord::Base  
set\_table\_name ‘gc\_edifici\_attivita’  
has\_and\_belongs\_to\_many :jobs, :join\_table =\>  
‘gc\_edificio\_avvio\_commessa’, :foreign\_key =\>  
‘edificio\_attivita\_gc\_id’, :class\_name =\> ‘Job’

end

class Job \< ActiveRecord::Base  
set\_table\_name ‘gc\_avvio\_commessa’

has\_and\_belongs\_to\_many :buildings, :join\_table  
=\>‘gc\_edificio\_avvio\_commessa’, :foreign\_key =\>  
‘commessa\_id’, :class\_name =\> ‘Building’, :association\_foreign\_key =\>  
‘edificio\_attivita\_gc\_id’  
end

Ok, table names are in Italian… that’s because I had to use a legacy  
database and could not change the tables’ names.

Now, for each Job, I have to list all the Buildings related to it. So  
it goes like this:

@jobs = Job.all

@jobs.each do |job|  
job.buildings [… do something with the buildings…]  
end

Everything goes well so far. But sometimes, I have to list only the  
Jobs happening on a given Building, yielding:

@jobs = Building.find(params[:building]).jobs  
@jobs.each do |job|  
job.buildings [… do something with the buildings…]  
end

This won’t work anymore; Rails keeps telling me there’s no such method  
as ‘buildings’ for class ‘Job’. it’s almost as if collecting the Jobs  
from a Building through HABTM, Rails cannot ‘see’ what methods are in  
class Job.

Any ideas about this? Is there a bug in Rails, or is this supposed to  
happen?  
Thanks in advance to anyone who might help me.

Regards,  
Rey9999

---

<div class="post-metadata">

**Author:** ![Rey9999](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/8e8cbc/32.png) [@Rey9999](https://www.ruby-forum.com/u/Rey9999)\
**Post date:** [November 7, 2008, 10:02pm UTC](https://www.ruby-forum.com/t/strange-bug-in-has-and-belongs-to-many/152812/2 "2008-11-07T22:02:46Z")

</div>

Under your Job class you have an association\_foreign\_key, do you need a  
comparable line under your building class as well? This will depend on  
what your join table looks like.

Otherwise, I don’t see any problems.
