views:

124

answers:

1

In my app, an Event has multiple items associated with it, potentially all of different types. For example, a "User ate a Banana" Event would have a User and a Banana associated with it.

It seems like one way to accomplish this would be to have a polymorphic join table with 3 fields: event_id, attachable_type, and attachable_id, where attachable is the polymorphic type.

Is this possible and/or am I way off base here?

+1  A: 

I usually use the has_many_polymorphs plugin for this. On m.onkey.org is a great article on that. You need a join table and than could write something like in event.rb for example:

has_many_polymorphs :items, :from => [:users, :bananas]

bananas.rb than would have something like

belongs_to :event belongs_to :item, :polymorphic => true

Something I tend to forget is that although banana only belongs to one event you still will have to call banana_instance_1.events (notice the plural!). That's weird but works. If you call .event you get nil

ajmurmann