Link to home
Create AccountLog in
Avatar of renderbox
renderboxFlag for United States of America

asked on

has_many :through, using the same table

I am attempting to do something that I should be able to do but I am having a hard time wrapping my head around it.  Normally I would do a HABTM table and that would be the end of it but I am trying to do something more complicated then HABTM can handle.

Here's an example:

I have one table that contains people.  Some of these people are sellers and some are buyers.  The catch is that sellers can be buyers and buyers can be sellers so their records are stored in the same table.  The second part of this is that I will need to add specific information to the connecting table that is unique to each connection, hence the need for a "has_many :through".

What I need to figure out is two things:

1) how to set up the relationships in the activeRecord object.

class Person < ActiveRecord::Base
      belongs_to :connection
end

class Connection < ActiveRecord::Base
      has_many :sellers, :through => ???
      has_many :buyers, :through => ???
end

2) how to exactly query this to get the results I am looking for.

connectedSellers = Person.find(:all, :condition => ["buyer_id = ?",buyerID])

connectedBuyers = Person.find(:all, :condition => ["seller_id = ?",sellerID])

connectedSellers.sellers.count
connectedBuyers.buyers.count


Thanks,
Grant

Avatar of renderbox
renderbox
Flag of United States of America image

ASKER

This seems like a hack way to possibly get more than one table but can anyone see a reason why I can not create a second ActiveRecord object that points back to the same database?

class Buyers < ActiveRecord::Base
      set_table_name "people"
end

class Sellers < ActiveRecord::Base
      set_table_name "people"
end



Grant
ASKER CERTIFIED SOLUTION
Avatar of wesgarrison
wesgarrison
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
wesgarrison,

That was exactly what I was looking for.  My problem was that I was not thinking along the lines of having the Seller & Buyer inherit the Person class.

Both answers solve the problem I had.

Thanks,
Grant
Sweet! Glad to help.