Model with two associations?

Hello!

I'm stumped on this one and after lots of searching and reading I need some help, please!

I'm trying to model a "purchase" as occurring between a "seller" and a "buyer", both of which are instances of a User class.

I have:

Ryan,

Thanks for the attempt. It didn't work, though. Unless I have the "purchases" class set wrong. If I manually create a record in the DB, with two users and one purchase, one as the seller and one as the buyer... and then do:

User.find(1).sales or User.find(1).purchases

I get an error that it is looking for "purchases.seller_type or purchases.buyer_type. But if they are both "User", can't that be set somewhere rather than having seller_type and buyer_type fields on the purchases table?

Actually, I tried setting the seller_type and buyer_type fields on the purchases table and it sort-of works. If I manually create a purchase entry and populate the fields in the DB record, and put "User" for the type fields, then it works. But, if I create a new purchase and give it two users, it creates the record but puts "NULL" in the purchases table for the seller_type and buyer_type. How would these get set to "User"? Or does that need to happen manually?

-Dan

On the User class? or the Purchase class? I tried it on both and it didn't seem to make a difference... still created the type fields as NULL.

Hmmm... I guess I could explicitly set them: purchase.seller_type = "User" (for example)

But it seems like there's gotta be a cleaner way to set 'em up and have that happen automagically.

:slight_smile:

-Dan

DOH!

Josh, I've read your stuff a TON! (It's really helped me catch up with Rails) I can't believe I didn't think of that very post. I'm gonna go refactor the code that way as it looks like _exactly_ what I need.

Thanks!

-Dan

Josh,

Is your example only for Rails 2.0? I'm on 1.2.5, although I probably should just get the 2.0 RC I guess.

-Dan

Haha! Yup, jumped on 2.0 RC and it works just fine. Well, this app is a long way out from production, so I guess I'll keep it on 2.0.

Nice!

Thanks, all!

User.find(:first).sales.first # => the first purchase object. Whee!

-Dan