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

I am creating an application that allows you to send comments on 5 unique models (messages, photos, events, etc.), with 2 or 3 in transit. Basically, each model has an associated comment model (PostComments, PhotoComments, EventComments, etc.), although the comments themselves are usually the same for all models.

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

While polymorphic associations clear code and redundancy, how do they affect performance? I know little about database optimization, but it seems to take longer to request a comment of 1,000,000 lines in a common comment table than 200,000 lines in a specific comment table. Should I switch to polymorphic associations (while the application is still at a relatively early stage of development), or should I continue to create models / tables for each type of comment?

+6
ruby-on-rails polymorphic-associations
source share
2 answers

It really depends on how big the site will be. First you need to add an index in 2 columns.

add_index :comments, [:commentable_type, commentable_id] 

This will significantly increase speed.

If you have a problem with great speed in the future, because you have 1,000,000 comments, you can always use caching or even wrap over multiple tables. But in fact, you will need a lot of comments in order to have speed problems. While you index your table! To fulfill a search query of 1,000,000 records, in any case, this is not so.

I say make 1 table!

+3
source share

Michael's answer will improve slightly:

 add_index :comments, [:commentable_id, :commentable_type] 

I think this answer would be better because: a commentable_id attribute would narrow the request more, which means that the overall speed of the request by index will be much faster. Give me feedback on this :)

0
source share

All Articles