aguynamedloren
aguynamedloren

Reputation: 2273

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?

Upvotes: 6

Views: 801

Answers (2)

CoderSpinoza
CoderSpinoza

Reputation: 2165

A little improve over Michael's answer:

add_index :comments, [:commentable_id, :commentable_type]

I think this answer would be better because :commentable_id attribute would narrow down the query more, which means that the overall query speed over the index would be a lot faster. Give me feedbacks on this :)

Upvotes: 0

Michael Koper
Michael Koper

Reputation: 9791

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!

Upvotes: 3

Related Questions