Forum: Ruby on Rails strange bug in has_and_belongs_to_many

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F736df208b5652ff5522c6c3063abb86?d=identicon&s=25 Rey9999 (Guest)
on 2008-11-07 16:59
(Received via mailing list)
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
9371e1a4eaee1cb75e856bcafe7d64a5?d=identicon&s=25 Marli Ba (marli03)
on 2008-11-07 22:02
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.
This topic is locked and can not be replied to.