Linking two belongs_to associations through a common class

I’m new and I just trying to figure out something about associations.
The following ruby code works but does not work in my actual rails
application. Am I doing something wrong or is there a reason why I
need to always use an extra table for a has_many_and_belongs_to
relationship? When I try this is Rails its willing to do a part of
this
(e.g, e.department) but not the last ‘.customers’ part? I could of
course just to x = e.department and then do x.customers (which does
work in Rails) but why do I need to do this in two steps instead of
one? I can see that for large datasets why the additional table would
help but if the dataset is small why do you need the extra table/
steps?

require ‘rubygems’;require ‘active_record’; require ‘mysql’;
ActiveRecord::Base.establish_connection(:adapter =>
‘mysql’, :database => “idea”, :username => “myname”, :password =>
‘mypswd’)

class Employee < ActiveRecord::Base
belongs_to :department
end
class Department < ActiveRecord::Base
has_many :departments
has_many :comments
end
class Customers < ActiveRecord::Base
belongs_to :department
end
e = Employee.find(1)
#to find the number of customers associated with a particular employee
within a department
p e.department.customers.size

Not sure if you missed something out in your code above but you’ll need
the has_many :customers in the Department class to do this e.g.

class Department < ActiveRecord::Base
has_many :customers
end

Then you can do:
e = Employee.find(1)
p e.department.customers.size

Don’t forget to add has_many :employees too if you want to do the
reverse (i.e. cust.department.employees)

Cheers
Luke

Luke P. wrote:

Not sure if you missed something out in your code above but you’ll need
the has_many :customers in the Department class to do this e.g.

class Department < ActiveRecord::Base
has_many :customers
end

Then you can do:
e = Employee.find(1)
p e.department.customers.size

Don’t forget to add has_many :employees too if you want to do the
reverse (i.e. cust.department.employees)

Cheers
Luke

No, that was just a typo. The code works if you replace :comments with
customers and of course class Customers < ActiveRecord::Base should be
class Customer < ActiveRecord::Base

This does work in Rails for the following reason.class Customers <
ActiveRecord::Base and to my great shame, I’d actually
read this article
http://blog.hasmanythrough.com/2008/2/27/count-length-size

In rails, you need to use .count and not .size for this to work
because the first collection has already been loaded and therefore you
are asking for the length and not the count! The length == 0 and so
no records are returned. Problem solved!