how to avoid polymorphic associations

删除回忆录丶 提交于 2019-12-03 02:33:26

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.

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.

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