Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comments for many different models: polymorphic or not? (Ruby on Rails)

I am building an app that allows comments on 5 unique models (Posts, Photos, Events, etc), with 2 or 3 more on the way. As it stands, each model has an associated comment model (PostComments, PhotoComments, EventComments, etc), though the comments themselves are generally the same across all models.

I recently discovered the power of polymorphic associations, explained perfectly in Railscast #154, which would essentially combine many models into a single model and many tables into a single table.

While polymorphic associations would clean up code and redundancy, how do they affect performance? I don't know much about database optimization, but it seems like it would take longer to query a comment from 1,000,000 rows in a generic comment table than 200,000 rows in a specific comment table. Is it worth making the switch to polymorphic associations (while the app is still relatively early in development) or should I continue making models/tables for each type of comment?

like image 934
aguynamedloren Avatar asked Apr 05 '11 07:04

aguynamedloren


1 Answers

It really depends how big the site will be. First you have to add a index on the 2 colums.

add_index :comments, [:commentable_type, commentable_id]

This will boost up the speed a lot.

If you have a big speed problem in the future because you have 1.000.000 comments you can always use caching or even migrate to several tables. But really you will need a lot of comments to have speed problems. As long if you index your table! To do a search query in 1.000.000 records isnt that much anyways.

I say, make 1 table!

like image 126
Michael Koper Avatar answered Sep 30 '22 07:09

Michael Koper