开发者

Rails Design Question - "Hot Right Now"

开发者 https://www.devze.com 2023-04-06 22:46 出处:网络
I have multiple models on my site. There are Suggestions and Items as well as Deals. I created a template which shows what is hot right now. I want to be able to apply this to all 3 models mentioned

I have multiple models on my site. There are Suggestions and Items as well as Deals.

I created a template which shows what is hot right now. I want to be able to apply this to all 3 models mentioned above and was wondering the best way to approach it.

Obviously, I can add "hotness_score" on each of this model, and then run cron to update their hotness score every hour (by my own algorithm). However, the inconvenient thing about that is if I want to display the top ten hottest THINGS on my site, I might potentially have to take the top ten hottest object from each of these and then sort them in memory. (Even though I can cache them it doesn't sound really pleasant).

I have also thought about creating a new model, aka Hotness, which has the following attributes:

  1. Type
  2. object_id
  3. hotness_score
  4. last_updated

The good thing about this is that I only have to query for Hotness order_by 'hotness_score DESC'.limit(10) and I can get the top 10 of everything combined.

Do you think this is a good implementation? Do you see any problems with this?

Can someone shed some insights to a better approach开发者_如何学运维 to this problem? I welcome all suggestions.


Yes, I think what you're talking about is a polymorphic model. It's a pretty standard way to do this in Rails:

create_table :hot_things do |t|
  t.column :item, :polymorphic => true # item_id, item_type
  t.column :score
  t.timestamps
end

class HotThing < ActiveRecord::Base
  belongs_to :item, :polymorphic => true
end

Something like that?

0

精彩评论

暂无评论...
验证码 换一张
取 消