views:

96

answers:

1

Given you have to implement a news feed like the one seen in social networks, ex facebook. Currently I'm using a News class which has a polymorphic assocation which can be of any kind like Image, Comment, Friendship, GroupMembership, etc. Whenever an Object is created, as News is created too. It's working fine with AR but I get into trouble when I'd switch to DM or Sequel as both don't natevily support polymorphic associations and discourage it's usage.

One workaround would be to use a big SQL clause with lot's of UNIONs to merge all the different tables which should be considered as news. But this has some drawbacks, escpecially performance would be terrible.

So I wonder how to solve without polymorphic associations while still getting good performance and no other drawbacks, like having the possibility of adding meta data to a news?

+2  A: 

Disclaimer: I'm the lead developer of Sequel.

The best way to go about it usually depends on what types of things you want to do with the data. One way to go about it is to have foreign key columns for all possible relationships:

news:
  id
  ... (Other columns)
  image_id
  comment_id
  friendship_id
  group_membership_id

There is really no performance difference in doing things this way versus having a generic foreign key and storing a class name. For lazy loading, you just pick the one foreign key field that's not nil/NULL, and choose the appropriate association to load. For query-per-table eager loading, you just load all associations at once. This also is more flexible in that you can eagerly load using JOINs, which isn't possible with the polymorphic approach. Plus, you get the benefit of real referential integrity.

The one downside is that if you want to add more association types in the future, you need to add foreign keys to the table.

Jeremy Evans
Thanks...that's a real simple but good idea :-). It requires some changes to the model (returning the real association of the ref) but that should be ok :)
gucki