Looks to me that you don't have the right model relationships defined.

in order to do "e.department.customers", the Department class has to
know about the relationship with Customers.  You should have:

class Department < AR::Base
  has_many :customers
end

I think this should work, if everything else is set up properly.

If this doesn't work, ensure that you have the proper table fields
defined as well.  You will need a "department_id" field in the
customers table.

Also, the rails convention is to name model classes with the singular
version of the name.  So you will likely also want to change the class
name to

class Customer < AR::Base
  #...
end

This can be changed, but with what you provide, I don't see that you
changed it.

Good luck

Andrew


On Dec 14, 3:46 pm, Todd <[email protected]> wrote:
> 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

--

You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply via email to