I want to have the following relationships set up and, for the life of me, I can''t get the bloody things to work: class Company < ActiveRecord::Base has_many :clients, :class_name => ''Company'' has_many :suppliers, :class_name => ''Company'' end I have two tables set up called company_clients and company_suppliers that each contain company_id and either client_id or supplier_id. Any ideas on how I can get this to work? I''ve come up with workarounds for it but none of them are elegant and I''d much rather do it properly. Any help would be much appreciated. -- Posted via http://www.ruby-forum.com/.
On Tue, Jul 28, 2009 at 6:25 PM, Paul Graham<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:> class Company < ActiveRecord::Base > > has_many :clients, :class_name => ''Company'' > has_many :suppliers, :class_name => ''Company'' > > end > > I have two tables set up called company_clients and company_suppliers > that each contain company_id and either client_id or supplier_id.has_many (along with a belongs_to in the other class) if for a 1-n relation, but you are modelling an n-m relation. class Company < ActiveRecord::Base has_and_belongs_to_many :clients, :class_name => "Company", :join_table => :company_clients has_and_belongs_to_many :suppliers, :class_name => "Company", :join_table => :company_suppliers end I''m not entirely sure that this works, but it''s more likely to. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale
Rick Denatale wrote:> has_many (along with a belongs_to in the other class) if for a 1-n > relation, but you are modelling an n-m relation. > > class Company < ActiveRecord::Base > has_and_belongs_to_many :clients, :class_name => "Company", > :join_table => :company_clients > has_and_belongs_to_many :suppliers, :class_name => "Company", > :join_table => :company_suppliers > end > > I''m not entirely sure that this works, but it''s more likely to. > > -- > Rick DeNatale > > Blog: http://talklikeaduck.denhaven2.com/ > Twitter: http://twitter.com/RickDeNatale > WWR: http://www.workingwithrails.com/person/9021-rick-denatale > LinkedIn: http://www.linkedin.com/in/rickdenataleRick, thank you. With one small amendment, that does the job nicely. The only thing that was missing was ":association_foreign_key => :client_id" tacked onto the declaration (and a corresponding one for the suppliers). -- Posted via http://www.ruby-forum.com/.