简体   繁体   English

许多不同型号的评论:多态还是不多? (Ruby on Rails)

[英]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. 我正在构建一个应用程序,允许评论5个独特的模型(帖子,照片,事件等),还有2或3个在路上。 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. 目前,每个模型都有一个相关的评论模型(PostComments,PhotoComments,EventComments等),尽管评论本身在所有模型中通常是相同的。

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. 我最近发现了多态关联的强大功能,在Railscast#154中得到了很好的解释,它基本上将许多模型组合成一个模型,将许多表组合成一个表。

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. 我对数据库优化知之甚少,但似乎需要更长的时间来查询通用注释表中1,000,000行的注释,而不是特定注释表中的200,000行。 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? 是否值得切换到多态关联(虽然应用程序仍然处于开发阶段的早期阶段),还是应该继续为每种类型的评论制作模型/表格?

It really depends how big the site will be. 这真的取决于网站的规模。 First you have to add a index on the 2 colums. 首先,您必须在2个列上添加索引。

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. 如果您将来遇到大速度问题,因为您有1.000.000条评论,您可以随时使用缓存,甚至可以迁移到多个表格。 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. 要在1.000.000记录中进行搜索查询,不管怎样。

I say, make 1 table! 我说,做一张桌!

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. 我认为这个答案会更好,因为:commentable_id属性会缩小查询范围,这意味着整个查询速度会快得多。 Give me feedbacks on this :) 给我这个反馈:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM