你需要的是一个缓存列。
class AddRatingCacheToArticles < ActiveRecord::Migration
def self.up
add_column :articles, :rating_cache, :decimal, :default => 0.0
end
def self.down
remove_column :articles, :rating_cache
end
end
2)Article
定义的更新方法,该方法将做计数::
class Article < ActiveRecord::Base
has_many :ratings
def update_rating_cache
current_rating = ratings.where(:like => true).count.to_f/ratings.count.to_f
update_attribute(:rating_cache, current_rating)
end
end
3)设置回调
1)为了屁股缓存列创建迁移在Rating
触发update_rating_cache
方法时,他们保存:
class Rating < ActiveRecord::Base
belongs_to :article
after_save :update_article_rating_cache
after_destroy :update_article_rating_cache
def update_article_rating_cache
article.update_rating_cache if article
end
end
4)现在是超级容易被评级为你的物品进行分类:
class Article < ActiveRecord::Base
has_many :ratings
def self.by_ratings
order('rating_cache DESC')
end
def update_rating_cache
current_rating = ratings.where(:like => true).count.to_f/ratings.count.to_f
update_attribute(:rating_cache, current_rating)
end
end
和可以用作ActiveRelation!
祝你好运:)
是的,我想出了一个像这样的SQL。考虑到切换到mongodb或其他nosql,因为我们遇到了很多麻烦,让事情干净,快速和灵活。 – Hartator
我相信这个查询应该很快(取决于你的数据集的大小),并且肯定会推荐_cache列方法(下面列出)作为你最有效的解决方案。你可以通过将这个视图移到一个视图(下面还要介绍)来清理SQL,为你提供一些更清晰的rails代码。祝你好运 –