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:
- Type
- object_id
- hotness_score
- 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?
精彩评论