how to avoid polymorphic associations

£可爱£侵袭症+ 提交于 2019-12-20 12:21:24

问题


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(ActiveRecords) but I get into trouble when I'd switch to DM(DataMapper) 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?


回答1:


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.




回答2:


Here's a gem to maintain the referential integrity of Polymorphic Associations at the database level in Rails:

https://github.com/mkraft/fides

As of this posting there are adapters for SQLite3 and Postgresql.

Disclaimer: I wrote the gem.



来源:https://stackoverflow.com/questions/3050959/how-to-avoid-polymorphic-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!